package com.hnas.eCard.web;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnas.account.orm.Account;
import com.hnas.account.service.AccountService;
import com.hnas.activity.domain.ActivityParamConstants;
import com.hnas.activity.domain.ActivityType;
import com.hnas.activity.domain.Constants;
import com.hnas.activity.domain.StrategyResult;
import com.hnas.activity.orm.Activity;
import com.hnas.activity.orm.ActivityItem;
import com.hnas.activity.util.ActivityUtil;
import com.hnas.api.dto.DTOResult;
import com.hnas.api.server.PostConnServer;
import com.hnas.api.util.CommonUtil;
import com.hnas.common.domain.CommonStatus;
import com.hnas.common.domain.CoreTradeType;
import com.hnas.common.domain.DiscountType;
import com.hnas.common.interfacedsc.InterfaceDsc;
import com.hnas.common.outdto.GetBalanceReceive;
import com.hnas.common.outdto.GetTranByTranSnoForm;
import com.hnas.common.outdto.GetTranByTranSnoReceive;
import com.hnas.common.outdto.LinkNetTradeForm;
import com.hnas.common.outdto.LinkNetTradeReceive;
import com.hnas.common.outdto.SearchRecgPayInfoForm;
import com.hnas.common.outdto.SearchRecgPayInfoReceive1;
import com.hnas.common.outdto.TranUserQRCodeByHttpForm;
import com.hnas.common.util.CommonConstants;
import com.hnas.common.util.CommonReturn;
import com.hnas.common.util.CommonUtils;
import com.hnas.common.util.PostServerInfoGet;
import com.hnas.common.util.ResultCode;
import com.hnas.common.util.ResultMsg;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.eCard.domain.CardMarkConstant;
import com.hnas.eCard.orm.AccECard;
import com.hnas.eCard.orm.CardTrail;
import com.hnas.eCard.service.AccECardService;
import com.hnas.eCard.service.CardTrailService;
import com.hnas.eCard.service.dto.DTOQueryWXPayStatus;
import com.hnas.eastsquare.domain.ReduceType;
import com.hnas.eastsquare.orm.SediBalanceChangeRecord;
import com.hnas.eastsquare.orm.SedimentaryBalance;
import com.hnas.eastsquare.service.SediBalanceChangeRecordService;
import com.hnas.eastsquare.service.SedimentaryBalanceService;
import com.hnas.eastsquare.util.JedisPoolUtil;
import com.hnas.eastsquare.util.RandomUtil;
import com.hnas.oracle.orm.Mrch;
import com.hnas.oracle.service.CommomOracleService;
import com.hnas.oracle.service.HntEmployeeCardService;
import com.hnas.oracle.service.MrchService;
import com.hnas.tjhnaaw.orm.GenerateMrchTwoCode;
import com.hnas.tjhnaaw.service.GenerateMrchTwoCodeService;
import com.hnas.trade.domain.CreateDtoOrderType;
import com.hnas.trade.domain.DetailType;
import com.hnas.trade.domain.NotifyType;
import com.hnas.trade.domain.OrderStatus;
import com.hnas.trade.domain.OrderType;
import com.hnas.trade.domain.PayStatus;
import com.hnas.trade.domain.PaymentType;
import com.hnas.trade.domain.TradeRemindThread;
import com.hnas.trade.domain.TranState;
import com.hnas.trade.dto.DTOConfirmQRcodePayForm;
import com.hnas.trade.dto.DTOConfirmQRcodeReturn;
import com.hnas.trade.dto.DTOCreateOrderFormEcard;
import com.hnas.trade.dto.DTOOrder;
import com.hnas.trade.dto.DTOOrderDetail;
import com.hnas.trade.dto.DTORecord;
import com.hnas.trade.dto.DTOResultTransApp;
import com.hnas.trade.dto.DTOSearchTrans;
import com.hnas.trade.dto.DTOTradeRecord;
import com.hnas.trade.dto.intf.CreateOrderDetailBean;
import com.hnas.trade.dto.intf.CreateOrderInBean;
import com.hnas.trade.mapper.OrderMapper;
import com.hnas.trade.orm.AbnormalOrder;
import com.hnas.trade.orm.Order;
import com.hnas.trade.orm.OrderDetail;
import com.hnas.trade.orm.TradeRecord;
import com.hnas.trade.orm.TradeRecordDetail;
import com.hnas.trade.service.AbnormalOrderService;
import com.hnas.trade.service.OrderDetailService;
import com.hnas.trade.service.OrderService;
import com.hnas.trade.service.TradeRecordDetailService;
import com.hnas.trade.service.TradeRecordService;
import com.hnas.trade.util.OrderNoUtil;

import redis.clients.jedis.Jedis;

/**
 * 电子卡交易Controller
 * <p>
 * Title:ECardOrderController
 * </p>
 * <p>
 * Description:电子卡订单Controller
 * </p>
 * <p>
 * Componay:
 * </p>
 * 
 * @author zhd.yu
 * @date 2018-02-24 14:09:06
 */
@Controller
@RequestMapping("/ecard/trade")
public class ECardTradeController {

	private static Logger log = LoggerFactory.getLogger(ECardTradeController.class);
	private ObjectMapper objectMapper = new ObjectMapper();
	
	private static AtomicInteger lockItem = new AtomicInteger(1);
	
	//@Autowired
	//private JedisUtil jedisUtil;
	@Autowired
	private JedisPoolUtil jedisPoolUtil;
	@Autowired
	private CommomOracleService commonOracleService;
	@Autowired
	private HntEmployeeCardService hntEmployeeCardService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private MrchService mrchService;
	@Autowired
	private GenerateMrchTwoCodeService generateMrchTwoCodeService;
	@Autowired
	private PostConnServer postConnServerNew;
	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	private PostServerInfoGet postServerInfoGet;
	@Autowired
	private TradeRecordDetailService tradeRecordDetailService;
	@Autowired
	private AbnormalOrderService abnormalOrderService;
	@Autowired
	private TradeRecordService tradeRecordService;
	@Autowired
	private SediBalanceChangeRecordService sediBalanceChangeRecordService;
	@Autowired
	private AccECardService accECardService;
	@Autowired
	private CardTrailService cardTrailService;
	@Autowired
	private SedimentaryBalanceService sedimentaryBalanceService;

	/**
	 * 海航员工打折利率
	 */
	@Value("#{component['HH_emp_rate']}")
	private String HHEmpRate;
	/**
	 * 海航员工打折商户号
	 */
	@Value("#{component['HH_emp_rate_mrchs']}")
	private String HHEmpRateMrchs;
	@Value("#{component['is_create_redPacket']}")
	private String isCreateRedPacket;

	@Value("#{component['subCode']}") // 发卡类型
	private String subCode;

	@Value("#{component['trade_mrch_id']}") //
	private String tradeMrchId;

	@Value("#{component['min_consumption']}") // 最低消费
	private String minConSum;

	@Value("#{component['east_square_mrch_id']}") // 最低消费
	private String eastSquareMrchId;
	private String eastSquareReducePercent;// 东方广场减免百分比
	private String eastSquareSediPercent;// 东方广场沉淀百分比
	private String FreeMin;// 东方广场免单最小金额
	private String FreeMax;// 东方广场免单最大金额
	private String RandomMin;// 东方广场随机减最小金额
	private String RandomMax;// 东方广场随机减最大金额
	private String FreeOrderLimit;// 东方广场免单最大笔数
	private String RandomReduceConsumeMin;// 东方广场随机减最小消费金额
	private String FreeCount;// 东方广场免单笔数

	@Value("#{component['hb_virtual_mrch_id']}")
	private String hbVirtualMrchId;// 海贝虚拟商户
	@Value("#{component['hb_virtual_mrch_termno']}")
	private String hbVirtualMrchTermNo;// 海贝虚拟商户终端
	@Value("#{component['hb_virtual_psam_id']}")
	private String hbVirtualPsamId;

	/**
	 * 创建POS支付订单
	 * 
	 * @param request
	 * @throws JsonProcessingException
	 */
	@RequestMapping(value = "/createPosOrder", method = RequestMethod.POST)
	@ResponseBody
	public String createPosOrder(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String sendData = "", customData = "", mrchName = null, cardNo = null, mrchId = null, subCode = null,
				termNo = null;
		Long vipRate = 100l;// 1.vip打折率
		Long mchRate = 100l;// 2.商户打折率
		Long empRate = 100l;// 3.员工打折率： 海航员工 HHEmpRate
		Long needPay = 0l;// 应付金额
//		Jedis jedis = jedisUtil.getJedis();
		Jedis jedis = jedisPoolUtil.getJedis();
		String activityId = null;
		boolean posNormal = true;//正常pos的创建订单（排除贴卡脱机和贴卡联机）
		try {
			// 判断是否可用VIP和代金券(默认不能使用)
			boolean vipAndCouponUseStatus = false;
			// 接收参数
			sendData = request.getParameter("sendData");
			customData = request.getParameter("customData");
			// sendData和customData入参为空判断
			if (StringUtil.isEmpty(sendData) || StringUtil.isEmpty(customData)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			// 入参对象的转化
			CreateOrderInBean in = objectMapper.readValue(sendData, CreateOrderInBean.class);
			// 防止参数前后有空格
			mrchId = CommonUtil.trimSpecial(in.getMrch_id());
			subCode = CommonUtil.trimSpecial(in.getSub_code());
			cardNo = CommonUtil.trimSpecial(in.getCard_no());
			String accountId = CommonUtil.trimSpecial(in.getAccount_id());
			String orderType = CommonUtil.trimSpecial(in.getOrder_type());
			JSONObject cust = (JSONObject) JSON.parse(customData);
//			termNo = CommonUtil.trimSpecial(cust.getString("termNo"));
			termNo = CommonUtil.trimSpecial(in.getTerm_no());
			// 各项入参校验
			String dtoJudgeResult = createPOSORderParamsJudge(dtoResult, in, termNo);
			if (!ResultCode.SUCCESS.equals(dtoJudgeResult)) {
				return dtoJudgeResult;
			}
			if (StringUtil.isEmpty(cardNo)) {// 卡号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_124, null);
			}
			
			// 输入金额格式判定
			try {
				needPay = CommonUtils.getBigDecimal(Double.parseDouble(in.getNeed_pay()));
			} catch (Exception e) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_055, null);
			}
			if (StringUtil.isNotEmpty(cardNo)) {
				cardNo = cardNo.toUpperCase().replace("F", "");
			}
			String accno = commonOracleService.getAccnoByCardNo(cardNo, subCode);//根据卡号和科目号获取卡账户号
			// 通过接口获取有效活动
			Activity activity = postConnServerNew.getActivity(mrchId, termNo, subCode);
			if ("224101".equals(subCode) && (activity == null || activity.getActivityItem() == null
					|| activity.getActivityItem().size() <= 0)) {
				// 如果是脱机，且没有活动，就返回创建订单失败
				return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
			}
			if (("14".equals(orderType)
					|| "13".equals(orderType))
					&& (activity == null || activity.getActivityItem() == null
							|| activity.getActivityItem().size() <= 0)) {
				// 如果是脱机/贴卡联机，且没有活动，就返回创建订单失败
				return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
			}
			if ("224101".equals(subCode)||"14".equals(orderType)|| "13".equals(orderType)){
				posNormal = false;
			}
			String checkCard = checkCard(cardNo, accountId);//校验卡号是否正常，
			if(posNormal && (checkCard == null)) {//卡号不正确
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_045, null);
			}	
			// 实付金额
			Long realPay = needPay;
			Account account = null;
			if (StringUtil.isNotEmpty(in.getAccount_id())) {
				account = this.accountService.findById(in.getAccount_id());
			} else {
				//账户id不能为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			// 查找核心商户信息
			Mrch mch = this.mrchService.getMrchByMrchId(mrchId);
			if (null == mch) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_090, null);
			}
			mrchName = mch.getMRCH_NAME();// 得到商户名称
			// 查找合作商户
			// 查找商户折扣详细信息
			GenerateMrchTwoCode mrchDetail = this.generateMrchTwoCodeService.getMrchTwoCodeByMrchIdAndTermNo(mrchId,
					termNo);
			if (mrchDetail != null && StringUtil.isNotEmpty(mrchDetail.getDiscount()) && (posNormal) ) {//电子卡不支持商户折扣
				try {
					mrchName = mrchDetail.getMrchName();
					mchRate = Long.parseLong(mrchDetail.getDiscount());
				} catch (Exception e) {
					e.printStackTrace();
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_127, null);
				}
			}
			// 2.确定账户为海航员工
			if (isHhEmpRate(mrchId)) {
				if (StringUtil.isNotEmpty(account.getEmpId())) {
					empRate = Long.parseLong(HHEmpRate);
				}
			}
			// 3.账户为VIP，得到VIP折扣率（非合作商户不能使用vip和代金券）,如果是脱机交易，就不关心VIP打折相关
			DTOCreateOrderFormEcard form = POSOrderFormQROrderForm(in, termNo);
			// 创建订单对象
			DTOOrder orderDto = createDtoOrder(form, needPay, realPay, account, cardNo, mrchDetail,
					CreateDtoOrderType.POS_ORDER, mrchName, mrchId);
			orderDto.setAccNo(accno);
			
			StrategyResult strategyResult = null;
			if (activity == null) {// 没有活动
				// 策略增加vip打折，海航员工折扣，商户折扣信息。如果优活动，就不能使用优惠券；如果没有活动可以使用优惠券。
				strategyResult = activityDiscountStrategy(jedis, accno, orderDto.getOrderNo(), mrchId, termNo, needPay,
						null);
			} else {
				// 判断是否包含随机减活动
				if (ActivityUtil.hasRandomDerateActivity(activity.getActivityItem())) {
					// 东方广场随机减活动
					List<ActivityItem> items = activity.getActivityItem();
					ActivityItem item = items.get(0);
					JSONObject jo = item.getItemParam();
					eastSquareReducePercent = jo.getString(ActivityParamConstants.reduce_percent);// 东方广场减免百分比
					eastSquareSediPercent = jo.getString(ActivityParamConstants.sedi_percent);// 东方广场沉淀百分比
					FreeMin = jo.getString(ActivityParamConstants.free_min);// 东方广场免单最小金额
					FreeMax = jo.getString(ActivityParamConstants.free_max);// 东方广场免单最大金额
					RandomMin = jo.getString(ActivityParamConstants.radom_min);// 东方广场随机减最小金额
					RandomMax = jo.getString(ActivityParamConstants.radom_max);// 东方广场随机减最大金额
					FreeOrderLimit = jo.getString(ActivityParamConstants.free_order_limit);// 东方广场免单最大笔数
					RandomReduceConsumeMin = jo.getString(ActivityParamConstants.random_reduce_consume_min);// 东方广场随机减最小消费金额
					FreeCount = jo.getString(ActivityParamConstants.free_count);// 东方广场免单笔数
					orderDto.setActivityId(activity.getId());
					strategyResult = activityDiscountStrategy(jedis, accno, orderDto.getOrderNo(), mrchId, termNo,
							needPay, activity);
					DTOOrderDetail eastSquareOrderDetail = createEastSquareOrderDetail(orderDto, strategyResult);
					return createEastSquareOrder(orderDto, eastSquareOrderDetail, dtoResult);
				} else {
					orderDto.setActivityId(activity.getId());
					activityId = activity.getId();
					// 策略增加vip打折，海航员工折扣，商户折扣信息。如果优活动，就不能使用优惠券；如果没有活动可以使用优惠券。
					strategyResult = activityDiscountStrategy(jedis, accno, orderDto.getOrderNo(), mrchId, termNo,
							needPay, activity);
				}

			}
			if (!strategyResult.isFlag()) {// 返回创建订单失败
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_040, null);
			}
			try {
				// 计算活动最终优惠总金额
				List<CreateOrderDetailBean> activityDetailList = strategyResult.getOrderDetailList();
				Long discountAmount = calcuteTotalDiscount(activityDetailList);
				realPay = realPay - discountAmount;
				// 计算虚拟卡后台已有的优惠
				List<CreateOrderDetailBean> backendDetailList = backendDiscountStrategy(account,
						needPay - discountAmount, mchRate, empRate, mrchDetail);
				// 计算虚拟卡后台优惠总金额
				discountAmount = calcuteTotalDiscount(backendDetailList);
				realPay = realPay - discountAmount;
				orderDto.setRealPay(realPay);
				// 合并所有的优惠详情
				List<CreateOrderDetailBean> beans = new ArrayList<CreateOrderDetailBean>();
				beans.addAll(activityDetailList);
				beans.addAll(backendDetailList);
				// 保存订单和订单详情，如果异常，需要考虑并发回退问题
				Order order = orderService.saveQrcode(orderDto, beans);
				if (null == order) {
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_058, null);
				}
				// 查询返回参数
				DTOOrder dtoOrder = orderService.getByOrderNo(order.getOrderNo());
				List<OrderDetail> detailList = orderDetailService.findByOrderNo(order.getOrderNo());
				JSONObject dto = createReturnDetailJson1(dtoOrder, detailList);
				return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(dto));
			} catch (Exception e) {
				e.printStackTrace();
				log.info("保存活动异常：" + e.getMessage());
				if (activity != null && activity.getActivityItem() != null) {
					for (ActivityItem activityItem : activity.getActivityItem()) {// 如果在创建策略成功，创建活动异常的话，需要将笔数减一
						if (ActivityType.CGDZ.getType().equals(activityItem.getSubType())) {// 常规打折活动项
							String key = ActivityUtil.getCgdzActivityKey(activityId);
							jedis.decrBy(key, 1);
						}
					}
				}
				return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_CreateOrderNoHttp
					+ ",请求数据:入参为:" + sendData + "  出错:" + e);// 日志记录
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_058, null);
		} finally {

			log.info(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_CreateOrderNoHttp
					+ ",请求数据:入参为:" + sendData + "  返回参数:" + dtoResult);// 日志记录
//			jedisUtil.closeJedis(jedis);
			if(jedis != null) jedis.close();
		}
	}

	/**
	 * 创建二维码支付订单（不支持活动）
	 * 
	 * @param request
	 * @throws JsonProcessingException
	 */
	@RequestMapping(value = "/createQRcodeOrder", method = RequestMethod.POST)
	@ResponseBody
	public String createQrcodeOrder(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String sendData = "", mrchName = null, cardNo = null, mrchId = null, subCode = null, termNo = null;
		Long vipRate = 100l;// 1.vip打折率
		Long mchRate = 100l;// 2.商户打折率
		Long empRate = 100l;// 3.员工打折率： 海航员工 HHEmpRate
		Long needPay = 0l;// 应付金额
		try {
			// 判断是否可用VIP和代金券(默认不能使用)
			boolean vipAndCouponUseStatus = false;
			// 接收参数
			sendData = request.getParameter("sendData");
			System.out.println("sendData:"+sendData);
			// 入参为空判断
			if (StringUtil.isEmpty(sendData)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			DTOCreateOrderFormEcard in = objectMapper.readValue(sendData, DTOCreateOrderFormEcard.class);
			// 各项入参为空判断
			mrchId = CommonUtil.trimSpecial(in.getMrch_id());
			subCode = CommonUtil.trimSpecial(in.getSub_code());
			termNo = CommonUtil.trimSpecial(in.getTerm_no());
			cardNo = CommonUtil.trimSpecial(in.getCard_no());
			String judgeResult = createQrcodeOrderJudge(dtoResult, in);
			if (!ResultCode.SUCCESS.equals(judgeResult)) {
				return judgeResult;
			}
			// 输入金额格式判定
			try {
				needPay = CommonUtils.getBigDecimal(Double.parseDouble(in.getNeed_pay()));
			} catch (Exception e) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_055, null);
			}
			// 根据账户id查找用户
			Account account = this.accountService.findById(in.getAccount_id());
			if (null == account) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_011, null);
			}
			if (StringUtil.isNotEmpty(cardNo)) {
				cardNo = cardNo.toUpperCase().replace("F", "");
			}
			// 查询账户最新卡号
//			cardNo = this.accCardService.findNewestCardNo(account.getId());
			String checkCard = checkCard(cardNo, account.getId());//校验卡号是否正常，
			if(checkCard == null) {//卡号不正确
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_045, null);
			}	
			String accno = commonOracleService.getAccnoByCardNo(cardNo, subCode);// 根据卡号和科目号获取卡账户号
			Long realPay = needPay;
			// 查找核心商户信息
			Mrch mch = this.mrchService.getMrchByMrchId(in.getMrch_id());
			if (null == mch) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_090, null);
			}
			mrchName = mch.getMRCH_NAME();// 得到商户名称
			// 查找合作商户
			// 查找商户折扣详细信息
			GenerateMrchTwoCode mrchDetail = this.generateMrchTwoCodeService.getMrchTwoCodeByMrchIdAndTermNo(mrchId,
					termNo);
			if (mrchDetail != null && StringUtil.isNotEmpty(mrchDetail.getDiscount()) && CardMarkConstant.MAIN_CARD.equals(checkCard)) {
				try {
					mrchName = mrchDetail.getMrchName();
					mchRate = Long.parseLong(mrchDetail.getDiscount());
				} catch (Exception e) {
					e.printStackTrace();
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_127, null);
				}
			}
			// 2.确定账户为海航员工
			if (isHhEmpRate(mrchId)) {
				if (StringUtil.isNotEmpty(account.getEmpId())) {
					empRate = Long.parseLong(HHEmpRate);
				}
			}
			// 3.账户为VIP，得到VIP折扣率（非合作商户不能使用vip和代金券）,如果是脱机交易，就不关心VIP打折相关
			// 创建订单对象
			DTOOrder orderDto = createDtoOrder(in, needPay, realPay, account, cardNo, mrchDetail,
					CreateDtoOrderType.QRC_ORDER, mrchName, mrchId);
			orderDto.setAccNo(accno);

			// 计算虚拟卡后台已有的优惠
			List<CreateOrderDetailBean> qrBackendDiscountList = qrBackendDiscountStrategy(account, needPay,
					mchRate, empRate, mrchDetail);
			// 计算虚拟卡后台优惠总金额
			Long discountAmount = calcuteTotalDiscount(qrBackendDiscountList);
			realPay = realPay - discountAmount;
			orderDto.setRealPay(realPay);
			// 合并所有的优惠详情
			List<CreateOrderDetailBean> beans = new ArrayList<CreateOrderDetailBean>();
			beans.addAll(qrBackendDiscountList);
			// 保存订单和订单详情，如果异常，需要考虑并发回退问题
			Order order = orderService.saveQrcode(orderDto, beans);
			if (null == order) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_058, null);
			}
			// 查询返回参数
			DTOOrder dtoOrder = orderService.getByOrderNo(order.getOrderNo());
			List<OrderDetail> detailList = orderDetailService.findByOrderNo(order.getOrderNo());
			JSONObject dto = createReturnDetailJson1(dtoOrder, detailList);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(dto));
		} catch (Exception e) {
			e.printStackTrace();
			// 日志记录
			log.info(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_UserCreateQrcodeOrderNo
					+ ",请求数据:入参为:" + sendData + "  出错:" + e);
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_058, null);
		} finally {
			// 日志记录
			log.info(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_UserCreateQrcodeOrderNo
					+ ",请求数据:入参为:" + sendData + "  返回参数:" + dtoResult);
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getTradeRecordList", method = RequestMethod.POST)
	public String getTradeRecordList(HttpServletRequest request) {
		/*
		 * 包括微信虚拟卡以及电子卡的交易记录 微信虚拟卡： 电子卡： 条件：1.交易状态（正常、异常、所有）2.卡号（有卡号，所有卡号）
		 * 交易记录来源：mysql，核心oracle
		 */
		DTOResult dtoResult = new DTOResult();
		try {
			// 1、把查询条件准备好
			String toDay = DateUtil.dateToString(new Date());
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String account_id = CommonUtil.trim(jo.getString("account_id"));
			String card_no = CommonUtil.trim(jo.getString("card_no"));// 卡号
			String order_parent_type = CommonUtil.trim(jo.getString("order_parent_type"));
			String order_type = CommonUtil.trim(jo.getString("order_type"));
			String sub_code = CommonUtil.trim(jo.getString("sub_code"));// 查询科目号
			String tran_type = CommonUtil.trim(jo.getString("tran_type"));// 交易类型（大类）
			String tran_state = CommonUtil.trim(jo.getString("tran_state"));// 交易状态
			String last_tran_time = CommonUtil.trim(jo.getString("last_tran_time"));// 上一页最后一条记录的交易记录时间
			String page_size = CommonUtil.trim(jo.getString("page_size"));
			String page_no = CommonUtil.trim(jo.getString("page_no"));
			boolean isQueryTodayData = true;
			if (!last_tran_time.contains(toDay)) {
				isQueryTodayData = false;
			}
			if (StringUtil.isEmpty(account_id)) {
				log.info("账户id为空！");
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			if (StringUtil.isEmpty(last_tran_time)) {
				log.info("交易记录时间为空！");
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_126, null);
			}
			Account account = accountService.findById(account_id);
			if (null == account) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_011, null);// 查询不到用户
			}
			int pageSize = Integer.valueOf(page_size);
			int pageNo = Integer.valueOf(page_no);
			// 卡号条件
			String cardNos = card_no;
			if (StringUtil.isEmpty(card_no)) {
				cardNos = getAllECards(account_id);// TODO 找出所有卡1：找出微信虚拟卡2：找出电子卡
				if ("".equals(cardNos)) {// 卡号为空
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
			}
			// 科目号条件
			if (StringUtil.isEmpty(sub_code)) {
				sub_code = "224102,224101,224103";
			}
			List<TradeRecord> normalList = null;// abnormalOrderService
			List<AbnormalOrder> abnormalList = null;
			List<DTORecord> localList = new ArrayList<DTORecord>();// 本地交易记录
			// 2、查询mysql交易记录
			if (StringUtil.isEmpty(tran_state)) {// TODO 查询本地记录
				tran_state = TranState.Normal.getState() + "," + TranState.Rescinded.getState() + ","
						+ TranState.Returned.getState() + "," + TranState.Reversed.getState();

				localList = this.abnormalOrderService.findTradeRecordList(account_id, cardNos, order_parent_type,
						order_type, last_tran_time, tran_state, 0, pageSize, isQueryTodayData);
			} else if (TranState.Normal.getState().equals(tran_state)) {// TODO 查询正常交易记录
				normalList = this.tradeRecordService.findTradeRecordList(account_id, cardNos, order_parent_type,
						order_type, last_tran_time, 1, pageSize, isQueryTodayData);
			} else {// TODO 查询异常交易记录
				abnormalList = abnormalOrderService.findAbnormalOrderList(account_id, cardNos, order_parent_type,
						order_type, last_tran_time, 1, pageSize, tran_state, isQueryTodayData);
			}
			if (null != normalList && normalList.size() > 0) {
				DTORecord dtoRecord = null;
				for (TradeRecord record : normalList) {
					dtoRecord = new DTORecord();
					BeanUtils.copyProperties(record, dtoRecord);
					dtoRecord.setTranStatus(TranState.Normal.getState());
					localList.add(dtoRecord);
				}
			}
			if (null != abnormalList && abnormalList.size() > 0) {
				DTORecord dtoRecord = null;
				for (AbnormalOrder record : abnormalList) {
					dtoRecord = new DTORecord();
					BeanUtils.copyProperties(record, dtoRecord);
					localList.add(dtoRecord);
				}
			}
			// 3、查询oracle交易记录
			DTOSearchTrans dtoSearchTrans = null;
			List<DTOResultTransApp> coreList = null;
			if (isQueryTodayData) {
				dtoSearchTrans = new DTOSearchTrans();
				dtoSearchTrans.setCardNo(cardNos);
				dtoSearchTrans.setEndDate(DateUtil.dateToString1(new Date()));
				dtoSearchTrans.setEndPage(page_size);
				dtoSearchTrans.setStartDate(DateUtil.dateToString1(new Date()));
				dtoSearchTrans.setStartPage(page_no);
				dtoSearchTrans.setSubCode(sub_code);
				dtoSearchTrans.setTranState(tran_state);
				dtoSearchTrans.setTranType(tran_type);
				coreList = this.mrchService.searchTransAppNew(dtoSearchTrans);
			}
			// 4、合并排序
			List<DTORecord> result = mergeSort(account_id, order_parent_type, order_type, last_tran_time, pageSize,
					pageNo, localList, coreList, tran_state);

			// 若是当天就查询当天以前的
			if (isQueryTodayData) {
				// 如果当前页条数不够pageSize，则从前一天中取
				if (result.size() < pageSize) {
					// 查询前一天的交易记录
					Calendar cal = Calendar.getInstance();
					cal.set(Calendar.MILLISECOND, 0);
					cal.set(Calendar.SECOND, 0);
					cal.set(Calendar.MINUTE, 0);
					cal.set(Calendar.HOUR_OF_DAY, 0);
					String timeStr = DateUtil.dateTimeToString(cal.getTime());
					Integer num = pageSize - result.size();
					List<DTORecord> list2 = this.abnormalOrderService.findTradeRecordList(account_id, cardNos,
							order_parent_type, order_type, timeStr, tran_state, 0, num, false);
					if (null != list2 && list2.size() > 0) {
						for (DTORecord tr : list2) {
							if (StringUtil.isNotEmpty(tr.getTradeEndTime())) {
								result.add(tr);
							}
						}
					}
				}
			}
			// 排序
			Collections.sort(result, new Comparator<DTORecord>() {
				@Override
				public int compare(DTORecord o1, DTORecord o2) {
					return o2.getTradeEndTime().compareTo(o1.getTradeEndTime());
				}
			});
			// 如果结果即大于pageSize 去处后面其余的
			if (null != result && result.size() > pageSize) {
				result = result.subList(0, pageSize);
			}
			// 格式化返回值
			JSONObject resultJson = mapperToReturn(result);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(resultJson));
		} catch (Exception e) {
			e.printStackTrace();
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}

	/**
	 * 获取所有卡号
	 * 
	 * @param account
	 */
	private String getAllECards(String accountId) {
		String cardNos = "";
		StringBuilder sb = new StringBuilder("");
		AccECard vo = new AccECard();
		vo.setAccId(accountId);
		List<AccECard> eCardList = this.accECardService.findByECard(vo);
		if (eCardList != null && eCardList.size() > 0) {
			for (AccECard aec : eCardList) {
				sb.append(aec.getCardNo()).append(",");
			}
		}
		if (sb.length() > 0) {
			cardNos = sb.substring(0, sb.length() - 1);
		}
		return cardNos;
	}

	private JSONObject mapperToReturn(List<DTORecord> result) {
		JSONObject resultJson = new JSONObject();
		JSONArray ja = new JSONArray();
		for (DTORecord tr : result) {
			JSONObject temp = new JSONObject();
			temp.put("order_no", tr.getOrderNo());
			temp.put("order_parent_type", tr.getOrderParentType());
			temp.put("order_type", tr.getOrderType());
			temp.put("trade_time", tr.getTradeEndTime());
			temp.put("mrch_id", tr.getMrchId());
			temp.put("mrch_name", tr.getMrchName());
			temp.put("commidity_id", tr.getCommidityId());
			temp.put("commidity_name", tr.getCommidityName());
			temp.put("need_pay", tr.getNeedPay());
			temp.put("real_pay", tr.getRealPay());
			temp.put("balance", tr.getAfterTradeBalance());
			temp.put("core_trade_type", tr.getCoreTradeType());
			temp.put("core_trade_sub_type", tr.getCoreTradeSubType());
			temp.put("rech_channel", tr.getRechChannel());
			temp.put("sub_id", tr.getSubId());
			temp.put("is_op_tran", tr.getIsOpTran());
			temp.put("op_tran_status", tr.getOpTranStatus());
			temp.put("mobile_phone", tr.getMobilePhone());
			temp.put("op_telecom_type", tr.getOpTelecomType());
			temp.put("op_product_id", tr.getOpProductId());
			temp.put("op_product_type", tr.getOpProductType());
			temp.put("card_no", tr.getCardNo());
			temp.put("tran_state", tr.getTranStatus());
			ja.add(temp);
		}
		resultJson.put("trade_list", ja);
		return resultJson;
	}

	private List<DTORecord> mergeSort(String account_id, String order_parent_type, String order_type,
			String last_tran_time, int pageSize, int pageNo, List<DTORecord> localList,
			List<DTOResultTransApp> coreList, String tran_state) {
		Map<String, DTORecord> tempMap = new HashMap<String, DTORecord>();
		List<DTORecord> result = new ArrayList<DTORecord>();
		// 将流水号放入map中，方便查找
		if (null != localList && localList.size() > 0) {
			for (DTORecord tr : localList) {
				if (StringUtil.isNotEmpty(tr.getTradeSno())) {
					tempMap.put(tr.getTradeSno(), tr);
				}
				if (StringUtil.isNotEmpty(tr.getTradeEndTime())) {
					result.add(tr);
				}

			}
		}
		// 作比较格式化所有返回值
		if (null != coreList && coreList.size() > 0) {
			mapperToDTORecord(order_parent_type, last_tran_time, coreList, tempMap, result, tran_state,account_id);
		}

		return result;
	}

	private void mapperToDTORecord(String order_parent_type, String last_tran_time, List<DTOResultTransApp> coreList,
			Map<String, DTORecord> tempMap, List<DTORecord> result, String tran_state,String account_id) {
		for (DTOResultTransApp dto : coreList) {
			if (CoreTradeType.LinkNetTrade_Cancel.getType().equals(dto.getTRAN_TYPE())
					&& TranState.Normal.getState().equals(dto.getTRAN_STATE())) {
				continue;
			}
			if (CoreTradeType.Core_Reject.getType().equals(dto.getTRAN_TYPE())
					&& TranState.Normal.getState().equals(dto.getTRAN_STATE())) {
				continue;
			}
			//TODO 先判断当前是否有该流水号的交易记录，如果有，就不处理了
			TradeRecord findByTradeSno = this.tradeRecordService.findByTradeSno(dto.getTRAN_SNO());
			if(findByTradeSno != null) continue;
			if (tempMap.size() > 0) {
				if (tempMap.containsKey(dto.getTRAN_SNO())) {
					DTORecord tr = tempMap.get(dto.getTRAN_SNO());
					tr.setCoreTradeSubType(dto.getTRAN_TYPE());
					tr.setCoreTradeType(dto.getTRAN_SUB_TYPE());
					tr.setRechChannel(dto.getRECH_CHANNEL());
					tr.setSubId(dto.getPAYMENT());
					tr.setIsOpTran(dto.getIS_OP_TRAN());
					tr.setOpTranStatus(dto.getORDER_STATUS());
					tr.setMobilePhone(dto.getMOBILE_PHONE());
					tr.setOpTelecomType(dto.getOP_TELECOM_TYPE());
					tr.setOpProductId(dto.getOP_PRODUCT_ID());
					tr.setOpProductType(dto.getOP_PRODUCT_TYPE());
					tr.setCardNo(dto.getCARD_NO());
					// 若存在状态不一致，即该条记录可能被撤销或退货
					if (!tr.getTranStatus().equals(dto.getTRAN_STATE())) {
						AbnormalOrder abnormalOrder = new AbnormalOrder();
						BeanUtils.copyProperties(tr, abnormalOrder);
						// 删除record表中的、添加一条新的异常
						try {
							abnormalOrder.setTranStatus(dto.getTRAN_STATE());
							tradeRecordService.updateAndAddAbrcord(dto.getTRAN_SNO(), abnormalOrder);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					tr.setTranStatus(dto.getTRAN_STATE());
					continue;
				}
			}

			// 核心数据筛选
			// 1. 时间筛选
			if (DateUtil.dateTimeToString(CommonUtils.getTranTime(dto.getTRAN_DATE(), dto.getTRAN_TIME()))
					.compareTo(last_tran_time) < 0) {
				OrderType orderType = OrderType.getByCore(dto.getTRAN_TYPE(), dto.getTRAN_SUB_TYPE());
				if (null != orderType) {
					if (OrderType.Reject.getType().equals(orderType.getType())) {
						dto.setTRAN_STATE(TranState.Returned.getState());
					}

					if (OrderType.Cancel.getType().equals(orderType.getType())) {
						dto.setTRAN_STATE(TranState.Rescinded.getState());
					}

					if (OrderType.CZ.getType().equals(orderType.getType())) {
						dto.setTRAN_STATE(TranState.Reversed.getState());
					}
					// 由于如果正常撤销，退货，核心那边也会将这些记录变为正常，如果筛选条件为正常，应该将这些去除
					if (TranState.Normal.getState().equals(tran_state)) {
						if (!TranState.Normal.getState().equals(dto.getTRAN_STATE())) {
							continue;
						}
					}
					// System.out.println("state:"+dto.getTRAN_STATE()+",ordertype:"+orderType.getDescription());
					if (StringUtil.isEmpty(order_parent_type)) {// 查询所有
						mapperCoreData(result, dto, orderType,account_id);
					} else {// 2.大类筛选
						if (order_parent_type.equals(orderType.getParentType())) {
							mapperCoreData(result, dto, orderType,account_id);
						}
					}
				}
			}
		}
	}

	private void mapperCoreData(List<DTORecord> result, DTOResultTransApp dto, OrderType orderType,String account_id) {
		if("11".equals(dto.getTRAN_TYPE()) && "01".equals(dto.getTRAN_SUB_TYPE())) {
			//TODO 判断交易时间的账户id。判断交易时间之后是否有转赠记录，如果没有，账户id不变；如果有，取距离交易时间最近的转赠记录的赠送人id作为账户id
			List<CardTrail> cardTrailListOverTranDate = this.cardTrailService.listByCardAndDate(dto.getCARD_NO(),DateUtil.dateTimeToString(CommonUtils.getTranTime(dto.getTRAN_DATE(), dto.getTRAN_TIME())));
			//判断最先一次赠送人的id和account_id是否一致，不一致就不显示
			if(cardTrailListOverTranDate != null && cardTrailListOverTranDate.size() > 0 && !cardTrailListOverTranDate.get(0).getSendAccId().equals(account_id)) {
				return;
			}
		}
		DTORecord tr = new DTORecord();
		tr.setOrderNo(dto.getTRAN_SNO());
		tr.setOrderType(orderType == null ? null : orderType.getType());// 可能需要根据核心的大类小类来区分
		tr.setOrderParentType(orderType == null ? null : orderType.getParentType());// 可能需要根据核心的大类小类来区分
		tr.setTradeEndTime(DateUtil.dateTimeToString(CommonUtils.getTranTime(dto.getTRAN_DATE(), dto.getTRAN_TIME())));
		tr.setMrchId(dto.getTRAN_MRCH());
		tr.setMrchName(dto.getTRAN_MRCH());
		tr.setCommidityId(null);
		tr.setCommidityName(null);
		tr.setNeedPay(Math.abs(Double.valueOf(dto.getTRAN_AMT()).longValue()));
		tr.setRealPay(Math.abs(Double.valueOf(dto.getTRAN_AMT()).longValue()));
		tr.setCoreTradeSubType(dto.getTRAN_SUB_TYPE());
		tr.setCoreTradeType(dto.getTRAN_TYPE());
		tr.setRechChannel(dto.getRECH_CHANNEL());
		tr.setSubId(dto.getPAYMENT());
		tr.setIsOpTran(dto.getIS_OP_TRAN());
		tr.setOpTranStatus(dto.getORDER_STATUS());
		tr.setMobilePhone(dto.getMOBILE_PHONE());
		tr.setOpTelecomType(dto.getOP_TELECOM_TYPE());
		tr.setOpProductId(dto.getOP_PRODUCT_ID());
		tr.setOpProductType(dto.getOP_PRODUCT_TYPE());
		tr.setCardNo(dto.getCARD_NO());
		tr.setTradeSno(dto.getTRAN_SNO());
		tr.setTranStatus(dto.getTRAN_STATE());
		tr.setAccId(account_id);
		if (StringUtil.isNotEmpty(tr.getTradeEndTime())) {
			result.add(tr);
		}

	}

	@RequestMapping(value = "/getSetActivityKeyValue", method = RequestMethod.POST)
	public void getSetActivityKeyValue(HttpServletRequest request) {
//		Jedis jedis = jedisUtil.getJedis();
		Jedis jedis = jedisPoolUtil.getJedis();
		try {
			String key = request.getParameter("key");
			String val = request.getParameter("val");
			if (StringUtil.isEmpty(key))
				return;
			String oldVal = jedis.get(key);
			System.out.println("===========key:" + key + ",oldval:" + oldVal + ",newval:" + val);
			if (StringUtil.isNotEmpty(val))
				jedis.set(key, val);
		} finally {
//			jedisUtil.closeJedis(jedis);
			if(jedis != null) jedis.close();
		}
	}

	@RequestMapping(value = "/qrOnBusTrade", method = RequestMethod.POST)
	@ResponseBody
	

	private String createPOSORderParamsJudge(DTOResult dtoResult, CreateOrderInBean in, String termNo) {
		if (!CommonUtils.supportSubcode(CommonUtil.trimSpecial(in.getSub_code()))) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_149, null);
		}
		// 校验账户ID，对于交易类型是01，02，03，04的订单，必须传账户id
		if (CommonUtils.isNeedAccount(CommonUtil.trimSpecial(in.getTrade_type()))
				&& StringUtil.isEmpty(in.getAccount_id())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
		}
		// 校验卡号
		if (StringUtil.isEmpty(in.getSub_code())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_074, null);
		}
		// 校验商户编号
		if (StringUtil.isEmpty(in.getMrch_id())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_089, null);
		}
		// 校验终端编号
		if (StringUtil.isEmpty(termNo)) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_080, null);
		}
		// 校验应付金额
		if (StringUtil.isEmpty(in.getNeed_pay())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_055, null);
		}
		// 校验二维码，对于POS扫用户消费必须传二维码
		if (CommonUtils.NEED_QRCODE_TRADETYPE.equals(CommonUtil.trimSpecial(in.getTrade_type()))
				&& StringUtil.isEmpty(in.getQrcode_no())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_046, null);
		}

		return ResultCode.SUCCESS;
	}

	/**
	 * 校验卡
	 * @Title: checkCard  
	 * @Description:  
	 * @param cardNo
	 * @param accountId
	 * @return
	 * @throws
	 */
	private String checkCard(String cardNo,String accountId) {
		if(StringUtil.isEmpty(cardNo)||StringUtil.isEmpty(accountId)) return null;
		AccECard vo = new AccECard();
		vo.setAccId(accountId);
		vo.setCardNo(cardNo);
		List<AccECard> ecards = this.accECardService.findByECard(vo);
		if(ecards != null && ecards.size() > 0) {
			return ecards.get(0).getCardNo();
		}
		return null;
	}

	/**
	 * 是否符合海航员工打折
	 * 
	 * @return
	 */
	public boolean isHhEmpRate(String mrchId) {
		List<String> hhRateMrchList = new ArrayList<String>();
		if (StringUtil.isNotEmpty(HHEmpRateMrchs)) {
			String[] strings = HHEmpRateMrchs.split(",");
			for (String s : strings) {
				hhRateMrchList.add(s);
			}
		}

		if (hhRateMrchList.contains(mrchId)) {
			return true;
		}

		return false;
	}

	private DTOCreateOrderFormEcard POSOrderFormQROrderForm(CreateOrderInBean in, String termNo) {
		DTOCreateOrderFormEcard form = new DTOCreateOrderFormEcard();
		form.setAccount_id(in.getAccount_id());
		form.setMrch_id(in.getMrch_id());
		form.setNeed_pay(in.getNeed_pay());
		form.setOrder_type(in.getOrder_type());
		form.setPasm_id(in.getPsam_id());
		form.setPayment(in.getPayment());
		form.setQrcode_no(in.getQrcode_no());
		form.setSub_code(in.getSub_code());
		form.setTerm_no(termNo);
		form.setTrade_type(in.getTrade_type());
		form.setCard_no(in.getCard_no());
		return form;
	}

	private DTOOrder createDtoOrder(DTOCreateOrderFormEcard in, Long needPay, Long realPay, Account account,
			String cardNo, GenerateMrchTwoCode mch, String type, String mrchName, String mrchId)
			throws Exception {
		DTOOrder orderDto = new DTOOrder();
		orderDto.setId(CommonUtils.getUUID());
		orderDto.setAccId(account.getId());
		orderDto.setAccName(account.getUserName());
		orderDto.setCardNo(cardNo);
		orderDto.setNeedPay(needPay);
		orderDto.setOrderNo(OrderNoUtil.createOrderNo(account.getId(), in.getOrder_type()));
		orderDto.setOrderStatus(OrderStatus.Unpay.getStatus());
		orderDto.setPayStatus(PayStatus.Unpay.getStatus());
		orderDto.setPayment(in.getPayment());
		orderDto.setOrderType(in.getOrder_type());
		orderDto.setOrderParentType(OrderType.getOrderType(in.getOrder_type()).getParentType());
		orderDto.setOrderTypeName(OrderType.getOrderTypeName(in.getOrder_type()));
		orderDto.setSubId(in.getSub_code());
		orderDto.setTradeType(in.getTrade_type());
		orderDto.setMrchId(mrchId);
		orderDto.setCreateTime(DateUtil.dateTimeToString(new Date()));
		orderDto.setUpdateTime(DateUtil.dateTimeToString(new Date()));
		orderDto.setIsDeleted(false);
		orderDto.setPsamId(in.getPasm_id());
		orderDto.setQrcodeNo(in.getQrcode_no());
		orderDto.setMrchName(mrchName);
		orderDto.setTermNo(in.getTerm_no());
		if (type.equals(CreateDtoOrderType.QRC_ORDER)) {
			orderDto.setCoreTradeType(CoreTradeType.LinkNetTrade_Proxy.getType());
			orderDto.setCoreTradeSubType(CoreTradeType.LinkNetTrade_Proxy.getSubType());
		} else {
			orderDto.setCoreTradeType(CoreTradeType.LinkNetTrade.getType());
			orderDto.setCoreTradeSubType(CoreTradeType.LinkNetTrade.getSubType());
		}

		// 查询当前余额,作为交易卡前余额
		CommonReturn con = postServerInfoGet.getBalanceInfo(cardNo, subCode);
		if (null != con && ResultCode.SUCCESS.equals(con.getResultCode())) {
			orderDto.setBeforeTradeBalance(((GetBalanceReceive) con.getResultData()).getBALANCE());
		}
		orderDto.setRealPay(realPay);
		return orderDto;
	}

	/**
	 * 生成活动优惠详情策略
	 * 
	 * @param accno
	 * @param orderNo
	 * @param mrchId
	 * @param termNo
	 * @param needPay
	 * @param activityItems
	 * @return
	 */
	private StrategyResult activityDiscountStrategy(Jedis jedis, String accno, String orderNo, String mrchId,
			String termNo, Long needPay, Activity activity) {
		StrategyResult strategyResult = new StrategyResult();
		strategyResult.setFlag(true);
		List<CreateOrderDetailBean> orderDetailList = new ArrayList<CreateOrderDetailBean>();
		strategyResult.setOrderDetailList(orderDetailList);
		List<ActivityItem> activityItems = null;
		if (activity == null)
			return strategyResult;
		String activityId = activity.getId();
		activityItems = activity.getActivityItem();
		if (activityItems == null || activityItems.size() == 0)
			return strategyResult;
		Long realPay = needPay;
		String dateStr = DateUtil.dateToString(new Date());
		// 先判断是否是会员日活动
		String vipday = activity.getVipday();
		String vipdayType = activity.getVipdayType();
		int vipdayDay = Integer.valueOf(activity.getVipdayDay());
		boolean flag = hasActivity(vipday, vipdayType, vipdayDay);
		if (flag == true) {
			for (ActivityItem activityItem : activityItems) {
				// 根据不同的活动类型进行处理
				if (ActivityType.CGDZ.getType().equals(activityItem.getSubType())) {// 常规打折活动项
					JSONObject paraObj = activityItem.getItemParam();
					Long commonDiscount = paraObj.getLong(ActivityParamConstants.common_discount);
					Long commonDiscountCount = paraObj.getLong(ActivityParamConstants.common_discount_count);
					Long commonDiscountLimit = paraObj.getLong(ActivityParamConstants.common_discount_limit);
					// 第一步，根据商户号、终端、活动id和当前日期查询交易记录数
					// int countByActivity =
					// this.orderService.getCountByActivity(mrchId,termNo,activity.getId(),dateStr);
					String key = ActivityUtil.getCgdzActivityKey(activityId);
					Long countByActivity = jedis.incrBy(key, 1);// 如果没有key，执行该方法会返回1
					log.info("常规打折：key-" + key + ",val=" + countByActivity);
					Long discountAmount = realPay - CommonUtils.getBigDecimal((realPay * commonDiscount / 100.0));
					discountAmount = discountAmount <= commonDiscountLimit ? discountAmount : commonDiscountLimit;// 优惠金额
					if (countByActivity <= commonDiscountCount && discountAmount > 0) {// 可以进行优惠
						try {
							realPay = realPay - discountAmount;// 实付金额
							createOrderDetail(orderDetailList, activityItem, DiscountType.DISCOUNT, commonDiscount,
									discountAmount);
						} catch (Exception e) {// 如果这部分代码异常，那么redis增加的次数需要减回来，并直接返回策略标识flag为false不创建订单了
							e.printStackTrace();
							log.info("商户-" + mrchId + "，终端-" + termNo + "，常规打折活动策略创建异常:" + e.getMessage());
							jedis.decrBy(key, 1);
							strategyResult.setFlag(false);
							return strategyResult;
						}
					} else {
						Long decrBy = jedis.decrBy(key, 1);
						log.info("常规打折活动次数超过域值，key-" + key + ",val=" + decrBy);
					}
				} else if (ActivityType.MJ1.getType().equals(activityItem.getSubType())) {// 满减优惠1活动项
					JSONObject paraObj = activityItem.getItemParam();
					Long fullcutMinAmount = paraObj.getLong(ActivityParamConstants.fullcut_min_amount);
					Long fullcutAmount = paraObj.getLong(ActivityParamConstants.fullcut_amount);
					Long fullcutCount = paraObj.getLong(ActivityParamConstants.fullcut_count);
					Long fullcutTotalCut = paraObj.getLong(ActivityParamConstants.fullcut_count_total);
					// 第一步，根据卡账户、活动id和当前日期查询交易记录数
					// 限制单个卡账户总共只能优惠的
					int countByActivity = this.orderService.getCountByAccno(accno, activityId, activityItem.getId(),
							dateStr);
					// 限制所有商户所有终端优惠的总笔数，redis
					// 第二步，如果没有达到上限，就判定金额是否达到最低消费金额，如果达到了，进行优惠
					if (countByActivity < fullcutCount) {
						// TODO 判断总笔数是否达到了
						String key = ActivityUtil.getMjActivityKey(activityId);
						Long totalCount = jedis.incrBy(key, 1);
						log.info("满减优惠1：key-" + key + ",val=" + countByActivity);
						if (totalCount <= fullcutTotalCut && realPay >= fullcutMinAmount) {
							try {
								Long discountAmount = realPay > fullcutAmount ? fullcutAmount : 1L;
								realPay = realPay - discountAmount;
								createOrderDetail(orderDetailList, activityItem, DiscountType.DERATE, null,
										discountAmount);
							} catch (Exception e) {
								e.printStackTrace();
								log.info("满减优惠1活动策略创建异常，redis数值回退:" + e.getMessage());
								jedis.decrBy(key, 1);
								strategyResult.setFlag(false);
								return strategyResult;
							}
						} else {
							Long decrBy = jedis.decrBy(key, 1);
							log.info("满减优惠1活动次数超过域值，key-" + key + ",val=" + decrBy);
						}
					}
				} else if (ActivityType.SJJ.getType().equals(activityItem.getSubType())) {
					// 满减活动项
					createOrderDetail(orderDetailList, activityItem, DiscountType.DISCOUNT, 0L, null);
				}
			}
		}
		strategyResult.setOrderDetailList(orderDetailList);
		return strategyResult;
	}

	/**
	 * 生成后台优惠详情策略
	 * 
	 * @return
	 */
	private List<CreateOrderDetailBean> backendDiscountStrategy(Account account, Long needPay,
			Long mchRate, Long empRate, GenerateMrchTwoCode mrchDetail) {
		List<CreateOrderDetailBean> beans = new ArrayList<CreateOrderDetailBean>();
		Long realPay = needPay;
		Long minConsumption = Long.parseLong(minConSum);
		// 比较VIP折扣率，选择折扣率最小进行，并返回响应的对象
		CreateOrderDetailBean discountBean = CommonUtils.getMinDiscouRate(needPay, mchRate, empRate, mrchDetail);
		// System.out.println("商户折扣:"+mchRate+",VIP折扣:"+vipRate+",海航员工折扣:"+empRate+",最终使用折扣:"+discountBean);
		// 折扣金额
		Long disCountAmount = 0l;
		if (null != discountBean) {
			beans.add(discountBean);
			disCountAmount = discountBean.getDiscountAmount();
		}
		// 打折后得到实际支付金额
		realPay = needPay - disCountAmount;
		// 打折后有最低消费，满减可以为0
		if (realPay <= minConsumption) {
			realPay = minConsumption;
		}

		return beans;

	}

	/**
	 * 创建返回的订单信息和订单详情信息对象
	 * 
	 * @param order
	 * @param detailList
	 * @return
	 */
	private JSONObject createReturnDetailJson1(DTOOrder order, List<OrderDetail> detailList) {
		JSONObject jo = new JSONObject();
		jo.put("account_id", order.getAccId());
		jo.put("card_no", order.getCardNo());
		jo.put("mrch_id", order.getMrchId());
		jo.put("mrch_name", order.getMrchName());
		jo.put("mrch_type", order.getMrchType());
		jo.put("need_pay", order.getNeedPay().toString());
		jo.put("order_no", order.getOrderNo());
		jo.put("order_status", order.getOrderStatus());
		jo.put("payment", order.getPayment());
		jo.put("psam_id", order.getPsamId());
		jo.put("real_pay", order.getRealPay().toString());
		JSONObject detailObj = new JSONObject();
		JSONObject vip = null;
		JSONObject mrch = null;
		JSONArray coupons = null;
		JSONObject employee = null;
		if (detailList != null && detailList.size() > 0) {
			OrderDetail mrchDetail = null;
			OrderDetail vipDetail = null;
			OrderDetail employeeDetail = null;
			List<OrderDetail> couponDetails = new ArrayList<OrderDetail>();
			for (OrderDetail od : detailList) {
				if (DetailType.MrchDiscount.getKey().equals(od.getType())) {
					mrchDetail = od;
				} else if (DetailType.VIP.getKey().equals(od.getType())) {
					vipDetail = od;
				} else if (DetailType.COUPON.getKey().equals(od.getType())) {
					couponDetails.add(od);
				} else if (DetailType.EmpDiscount.getKey().equals(od.getType())) {
					employeeDetail = od;
				}
			}

			if (null != employeeDetail) {
				employee = new JSONObject();
				employee.put("product_name", employeeDetail.getProductName());
				employee.put("discount_value", employeeDetail.getDiscountValue());
				employee.put("discount_amount", employeeDetail.getDiscountAmount());
			}
			detailObj.put("employeeDetail", employee);

			if (mrchDetail != null) {
				mrch = new JSONObject();
				mrch.put("mrch_id", mrchDetail.getRelateId());
				mrch.put("mrch_name", order.getMrchName());
				mrch.put("term_no", order.getTermNo());
				mrch.put("discount_value", mrchDetail.getDiscountValue());
				mrch.put("discount_amount", mrchDetail.getDiscountAmount());
			}
			detailObj.put("mrch", mrch);
			if (vipDetail != null) {
				vip = new JSONObject();
				vip.put("product_id", vipDetail.getRelateId());
				vip.put("product_name", vipDetail.getProductName());
				vip.put("discount_type", vipDetail.getDiscountType());
				vip.put("discount_value", vipDetail.getDiscountValue());
				vip.put("discount_amount", vipDetail.getDiscountAmount());
			}
			detailObj.put("vip", vip);

			if (couponDetails.size() > 0) {
				coupons = new JSONArray();
				for (OrderDetail od : couponDetails) {
					JSONObject coupon = new JSONObject();
					coupon.put("coupon_id", od.getRelateId());
					coupon.put("coupon_type_name", od.getCouponTypeName());
					coupon.put("discount_type", od.getDiscountType());
					coupon.put("discount_value", od.getDiscountValue());
					coupon.put("discount_amount", od.getDiscountAmount());
					coupons.add(coupon);
				}
			}

			detailObj.put("coupons", coupons);
			jo.put("order_detail", detailObj);
		}

		return jo;
	}

	private boolean hasActivity(String vipday, String vipdayType, int vipdayDay) {
		boolean flag = false;
		if (Constants.ISVIPDAY.equals(vipday)) {// 是会员日活动
			// 判断是否满足会员日条件
			if (Constants.VIPDAY_WEEK.equals(String.valueOf(vipdayType))) {
				// 计算当天在本周数
				int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1;
				if (dayOfWeek == 0)
					dayOfWeek = 7;
				if (dayOfWeek == vipdayDay) {// 可以进行打折
					flag = true;
				}
			} else if (Constants.VIPDAY_DAY.equals(String.valueOf(vipdayType))) {
				int dayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
				if (dayOfMonth % 10 == vipdayDay) {// 可以进行打折
					flag = true;
				}
			} else if (Constants.VIPDAY_DAYOFMONTH.equals(String.valueOf(vipdayType))) {
				int dayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
				if (dayOfMonth == vipdayDay) {// 可以进行打折
					flag = true;
				}
			}

		} else {
			flag = true;
		}
		return flag;
	}

	/**
	 * 创建折扣订单详情对象
	 * 
	 * @param orderNo
	 * @param orderDetailList
	 * @param activity
	 * @param vipdayDiscount
	 * @param discountAmount
	 */
	private void createOrderDetail(List<CreateOrderDetailBean> orderDetailList, ActivityItem activityItem,
			String discountType, Long discount, Long discountAmount) {
		CreateOrderDetailBean bean = new CreateOrderDetailBean();
		bean.setCouponName(null);
		if (discountAmount != null)
			bean.setDiscountAmount(discountAmount);
		bean.setDiscountType(discountType);
		if (discount != null)
			bean.setDiscountValue(discount.toString());
		bean.setProductName(activityItem.getItemName());
		bean.setRaletedId(activityItem.getId());
		bean.setType(DetailType.ActivityDiscount.getKey());
		bean.setActivityItemType(activityItem.getSubType());
		orderDetailList.add(bean);// 将详情对象添加到详情集合中
	}

	/**
	 * 计算优惠总额
	 * 
	 * @param orderDetailList
	 * @return
	 */
	private Long calcuteTotalDiscount(List<CreateOrderDetailBean> orderDetailList) {
		Long discountAmount = 0l;
		if (orderDetailList == null || orderDetailList.size() <= 0)
			return discountAmount;
		for (CreateOrderDetailBean od : orderDetailList) {
			discountAmount += Long.valueOf(od.getDiscountAmount());
		}
		return discountAmount;
	}

	private String createEastSquareOrder(DTOOrder eastSquareOrder, DTOOrderDetail eastSquareOrderDetail,
			DTOResult dtoResult) {
		Long needPay = eastSquareOrder.getNeedPay();
		Long realPay = needPay;
//		Jedis jedis = jedisUtil.getJedis();
		Jedis jedis = jedisPoolUtil.getJedis();
		// 先减1%
		try {
			SediBalanceChangeRecord changeRecord = new SediBalanceChangeRecord();
			changeRecord.setOrderNo(eastSquareOrder.getOrderNo());
			Long discountAmt = CommonUtils.getBigDecimal(needPay * Long.valueOf(eastSquareReducePercent) / 100.0);
			changeRecord.setReturnAmount(discountAmt);
			if (discountAmt <= 0) {// 相当于没有减免
			} else {
				realPay = realPay - discountAmt;// 返利1%
			}
			long derateAmount = 0L;// 减免金额
			long temp = jedis.incrBy("eastSquareCount", 1);
			log.info("orderNo:" + eastSquareOrder.getOrderNo() + ",当前笔数:" + temp);
			if ((temp - 1) % Integer.valueOf(FreeCount) == 0
					&& (temp - 1) / Integer.valueOf(FreeCount) < Integer.valueOf(FreeOrderLimit)
					&& needPay >= Long.valueOf(FreeMin) && needPay <= Long.valueOf(FreeMax)) {// 每50笔免单0.1-50元
				// 符合免单条件
				changeRecord.setReduceType(ReduceType.Free.getType());
				derateAmount = realPay - 1;
				realPay = 1l;
			} else {
				// 不符合免单条件，判断余额池是否够减免2-6元
				long balance = jedis.decrBy("balance", 0);
				if (needPay < Long.valueOf(RandomReduceConsumeMin)) {// 小于20元，就不能优惠了
					// 不符合减免条件，无法减免
				} else {
					if (balance <= 0) {// 如果余额池中没有了，就无法减免了
						// 无法减免1
					} else {
						// 符合随机减免条件，调用随机减免算法，算出减免金额
						long count = jedis.incrBy("eastSquareCount", 0);
						long amount = jedis.incrBy("eastSquareAmount", 0);
						int randomX = RandomUtil.randomValue(amount, count);
						if (balance < randomX * 100) {
							// 无法减免2
						} else {
							realPay = realPay - randomX * 100L;
							derateAmount = randomX * 100L;
							changeRecord.setReduceType(ReduceType.RandomReduct.getType());
						}
					}
				}
			}
			eastSquareOrder.setRealPay(needPay - discountAmt - derateAmount);// 更新订单的实付金额
			String errCode = ResultCode.FAIL;
			if (discountAmt > 0 || derateAmount > 0) {
				// 保存一条记录，成功就成功，不成功回滚。然后jedis相应要加减回去
				changeRecord.setBalanceChange(derateAmount);
				changeRecord.setSedimentaryChange(discountAmt);
				String str = "";
				if (ReduceType.RandomReduct.getType().equals(changeRecord.getReduceType())) {
					str += "单笔优惠:" + discountAmt / 100.0 + "元,随机减免:" + derateAmount / 100.0 + "元";
				} else if (ReduceType.Free.getType().equals(changeRecord.getReduceType())) {
					str += "单笔优惠:" + discountAmt / 100.0 + "元,免单减免:" + derateAmount / 100.0 + "元";
				} else {
					str += "单笔优惠:" + discountAmt / 100.0 + "元";
				}
				changeRecord.setDescription(str);
				changeRecord.setId(CommonUtils.getUUID());
				changeRecord.setOperateTime(new Date());
				changeRecord.setIsDeleted("1");
				errCode = this.orderService.createEastSquareOrder(eastSquareOrder, eastSquareOrderDetail, changeRecord);
			} else {
				errCode = this.orderService.createEastSquareOrder(eastSquareOrder, eastSquareOrderDetail, null);
			}
			if (ResultCode.SUCCESS.equals(errCode)) {
				JSONObject result = createReturnDetailJson1(eastSquareOrder, null);// 返回订单信息
				return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(result));
			} else {
				return CommonUtils.createResult(dtoResult, errCode, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		} finally {// 最后关闭redis
//			jedisUtil.closeJedis(jedis);
			if(jedis != null) jedis.close();
		}
	}
	
	/**
	 * 微信支付状态回调
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("finally")
	@ResponseBody
	@RequestMapping(value = "/WXPayStatusCallBack", method = RequestMethod.POST)
	public String WXPayStatusCallBack(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String responseJson = "";
		try {
			while (true) {
				String sendData = request.getParameter("sendData");
				JSONObject jo = (JSONObject) JSON.parse(sendData);
				String swiftNumber = jo.getString("swift_number");
				if (StringUtil.isEmpty(swiftNumber)) {
					dtoResult.setResultCode(ResultCode.ERROR_050);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_050));
					break;
				}

				String payStatus = jo.getString("pay_status");
				if (StringUtil.isEmpty(payStatus)) {
					dtoResult.setResultCode(ResultCode.ERROR_049);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_049));
					break;
				}

				TradeRecord findByTradeSno = this.tradeRecordService.findBySwiftNumber(swiftNumber);
				if (findByTradeSno != null && StringUtil.isNotEmpty(findByTradeSno.getTradeSno())) {
					dtoResult.setResultCode(ResultCode.SUCCESS);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
					break;
				}

				// 根据swiftNumber获取订单
				DTOOrder orderDto = this.orderService.getBySwiftNumber(swiftNumber);
				if (null == orderDto) {
					dtoResult.setResultCode(ResultCode.ERROR_051);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_051));
					break;
				}

				orderDto.setPayStatus(payStatus);
				if (!OrderStatus.Payed.getStatus().equals(orderDto.getOrderStatus())) {
					orderDto.setOrderStatus(payStatus);
					orderDto.setPayEndTime(DateUtil.dateTimeToString(new Date()));
				}
				Order order = this.orderService.saveOrUpdate(orderDto);
				if (order == null) {
					dtoResult.setResultCode(ResultCode.ERROR_059);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_059));
					break;
				}

				// 存储交易记录
				DTOTradeRecord dtoTradeRecord = mapperRecord(orderDto);
				// 判断交易类型
				if (OrderType.Recharge.getType().equals(order.getOrderType())) {// 如果是充值
					// 查找tranSno
					SearchRecgPayInfoForm form = new SearchRecgPayInfoForm();
					form.setSwiftNumber(swiftNumber);
					SearchRecgPayInfoReceive1 searchRecgPayInfoReceive = postConnServerNew.getResultData(form,
							"APP_RechargeQuery", SearchRecgPayInfoReceive1.class);// 根据微信订单号查询微信支付结果
					if (null == searchRecgPayInfoReceive || (null != searchRecgPayInfoReceive
							&& StringUtil.isEmpty(searchRecgPayInfoReceive.getRechargeNum()))) {
						dtoTradeRecord = null;
					} else {
						String tranEndTime = searchRecgPayInfoReceive.getTransTime();
						// if(null!=tranEndTime&&tranEndTime.indexOf(".0")!=-1){
						// tranEndTime = tranEndTime.substring(0,
						// tranEndTime.lastIndexOf(".0"));
						// }
						orderDto.setPayEndTime(tranEndTime);
						orderDto.setTradeEndTime(tranEndTime);
						this.orderService.saveOrUpdate(orderDto);
						Account account = this.accountService.findById(orderDto.getAccId());
						JSONObject remindData = new JSONObject();
						remindData.put("openIdStr", account.getOpenId());
						remindData.put("modelType", "1");
						remindData.put("payValue", "￥" + orderDto.getRealPay() / 100.0);
						remindData.put("cardNo", orderDto.getCardNo());
						remindData.put("tranSno", orderDto.getOrderNo());
						remindData.put("tranTime", orderDto.getTradeEndTime());
						remindData.put("mrchName", orderDto.getMrchName());
						remindData.put("first", CommonConstants.FIRST_2);
						remindData.put("remark", CommonConstants.REMARK_1);
						TradeRemindThread tradeRemind = new TradeRemindThread(remindData);
						Thread thread = new Thread(tradeRemind);
						thread.start();
						dtoTradeRecord.setTradeEndTime(tranEndTime);
						dtoTradeRecord.setTradeSno(searchRecgPayInfoReceive.getRechargeNum());
					}
				}
				// 存储交易记录
				if (null == dtoTradeRecord) {
					dtoResult.setResultCode(ResultCode.ERROR_104);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_104));
					break;
				}
				TradeRecord tradeRecord = this.tradeRecordService.saveOrUpdate(dtoTradeRecord);
				if (tradeRecord == null) {
					// 存储交易记录失败
					dtoResult.setResultCode(ResultCode.ERROR_039);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_039));
					break;
				}
				dtoResult.setResultCode(ResultCode.SUCCESS);
				dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			dtoResult.setResultCode(ResultCode.FAIL);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.FAIL));
		} finally {
			try {
				// 返回响应
				responseJson = objectMapper.writeValueAsString(dtoResult);// 实体转json
			} catch (Exception e) {
				e.printStackTrace();
			}
			return responseJson;
		}
	}
	
	/**
	 * 提供前端查询订单状态的接口
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("finally")
	@ResponseBody
	@RequestMapping(value = "/queryWXPayStatus", method = RequestMethod.POST)
	public String queryWXPayStatus(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String responseJson = "";
		try {
			while (true) {
				String sendData = request.getParameter("sendData");
				JSONObject jo = (JSONObject) JSON.parse(sendData);
				String order_no = jo.getString("order_no");
				if (StringUtil.isEmpty(order_no)) {
					dtoResult.setResultCode(ResultCode.ERROR_048);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_048));
					break;
				}
				// 根据orderNo获取订单
				DTOOrder orderDto = this.orderService.getByOrderNo(order_no);
				if (null == orderDto) {
					dtoResult.setResultCode(ResultCode.ERROR_047);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_047));
					break;
				}
				DTOQueryWXPayStatus dtoQuery = new DTOQueryWXPayStatus();
				if (OrderStatus.Payed.getStatus().equals(orderDto.getOrderStatus())) {
					dtoQuery.setCommidity_name(orderDto.getCommidityName());
					dtoQuery.setCommidity_type(orderDto.getCommidityType());
					dtoQuery.setMrch_name(orderDto.getMrchName());
					dtoQuery.setNeed_pay(orderDto.getNeedPay().toString());
					dtoQuery.setOrder_no(orderDto.getOrderNo());
					dtoQuery.setOrder_status(orderDto.getOrderStatus());
					dtoQuery.setPayment(orderDto.getPayment());
					dtoQuery.setReal_pay(orderDto.getRealPay().toString());
					dtoQuery.setSub_id(orderDto.getSubId());
					dtoQuery.setSwift_number(orderDto.getSwiftNumber());
					dtoQuery.setTrade_end_time(orderDto.getTradeEndTime());
					dtoQuery.setTrade_sno(orderDto.getTradeSno());
					dtoQuery.setTrade_type(orderDto.getTradeType());
					dtoResult.setResultCode(ResultCode.SUCCESS);
					dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
					dtoResult.setResultData(objectMapper.writeValueAsString(dtoQuery));
					break;
				}
				dtoQuery.setOrder_status(OrderStatus.Unpay.getStatus());
				dtoResult.setResultCode(ResultCode.SUCCESS);
				dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
				dtoResult.setResultData(objectMapper.writeValueAsString(dtoQuery));
				break;
			}
		} catch (Exception e) {
			dtoResult.setResultCode(ResultCode.FAIL);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.FAIL));
		} finally {
			try {
				// 返回响应
				responseJson = objectMapper.writeValueAsString(dtoResult);// 实体转json
			} catch (Exception e) {
				e.printStackTrace();
			}
			return responseJson;
		}

	}
	
	/**
	 * 异步通知支付状态Notify
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("finally")
	@ResponseBody
	@RequestMapping(value = "/notifyPaymentStatus", method = RequestMethod.POST)
	public String notifyPaymentStatus(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String responseJson = "";
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String orderNo = jo.getString("order_no");
			String payStatus = jo.getString("pay_status");
			String tradeSno = jo.getString("trade_sno");
			String batchNo = jo.getString("batch_no");
			String posSno = jo.getString("pos_sno");
			if (StringUtil.isEmpty(orderNo)) {// 订单号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_048, null);
			}
			if (StringUtil.isEmpty(payStatus)) {// 支付状态为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_049, null);
			}
			if (!NotifyType.SUCCESS.getType().equals(payStatus) && !NotifyType.FAIL.getType().equals(payStatus)) {// 不是成功也不是失败状态
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_068, null);
			}
			DTOOrder order = orderService.getByOrderNo(orderNo);
			if (null == order) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_047, null);
			}
			if (NotifyType.SUCCESS.getType().equals(payStatus) && StringUtil.isEmpty(tradeSno)
					&& !"224101".equals(order.getSubId())) {// 支付成功但核心流水号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_065, null);
			}
			order.setBatchNo(batchNo);
			order.setPosSno(posSno);
			// 如果是脱机交易，根据成功还是失败保存订单
			if ("224101".equals(order.getSubId())) {
				Activity activity = postConnServerNew.getActivity(order.getMrchId(), order.getTermNo(),
						order.getSubId());
				if (activity != null && ActivityUtil.hasRandomDerateActivity(activity.getActivityItem())) {
					// 东方广场随机减活动
					if (OrderStatus.Payed.getStatus().equals(order.getOrderStatus())) {
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_001);
						return objectMapper.writeValueAsString(dtoResult);
					}

					if (OrderStatus.PayFail.getStatus().equals(order.getOrderStatus())) {
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_004);
						return objectMapper.writeValueAsString(dtoResult);
					}
					String cardNo = order.getCardNo();
					if (StringUtil.isEmpty(cardNo)) {
						return CommonUtils.createResult(dtoResult, ResultCode.ERROR_057, null);
					}
					boolean isNormal = false;
					if (PayStatus.Payed.getStatus().equals(payStatus)) {
						order.setTradeSno(tradeSno);// 通过核心流水号查询订单详情
						isNormal = true;
						order.setPayStatus(PayStatus.Payed.getStatus());
						order.setOrderStatus(OrderStatus.Payed.getStatus());
						order.setRemark(ResultMsg.MSG_003);
						order.setPayEndTime(DateUtil.dateTimeToString(new Date()));
						order.setTradeEndTime(DateUtil.dateTimeToString(new Date()));
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
						// 更新沉淀池和余额池
						synchronized (lockItem) {
							this.sedimentaryBalanceService.updateByOrderNo(orderNo, 1000 * 100L);
						}
					} else if (PayStatus.PayFail.getStatus().equals(payStatus)) { // 1、支付失败且无核心流水号
						order.setOrderStatus(OrderStatus.PayFail.getStatus());
						order.setRemark(ResultMsg.MSG_002);
						// 支付失败，需要将沉淀池和余额池金额回退
						dealEastSquareFailOrder(dtoResult, orderNo);
					}
					order.setUpdateTime(DateUtil.dateTimeToString(new Date()));
					// 保存当前的订单信息
					Order afterOrder = this.orderService.saveOrUpdate(order);
					if (isNormal) {
						// 查询当前余额
						CommonReturn con = postServerInfoGet.getBalanceInfo(cardNo, subCode);
						if (null != con && ResultCode.SUCCESS.equals(con.getResultCode())) {
							order.setAfterTradeBalance(((GetBalanceReceive) con.getResultData()).getBALANCE());
						}
						DTOTradeRecord tradeRecord = OrderMapper.getInstance().mapToDTOTradeRecord(afterOrder);
						if (null != tradeRecord) {
							tradeRecord.setId(CommonUtils.getUUID());
							log.info("notify");
							tradeRecordService.saveOrUpdate(tradeRecord);
						}
						// 保存订单详情
						List<OrderDetail> list = orderDetailService.findByOrderNo(orderNo);
						if (null != list && list.size() > 0) {
							TradeRecordDetail dto = null;
							for (OrderDetail detail : list) {
								dto = new TradeRecordDetail();
								BeanUtils.copyProperties(detail, dto);
								tradeRecordDetailService.save(dto);
							}
						}
					}

				} else {
					if (OrderStatus.Payed.getStatus().equals(order.getOrderStatus())) {
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_001);
						return objectMapper.writeValueAsString(dtoResult);
					}

					if (OrderStatus.PayFail.getStatus().equals(order.getOrderStatus())) {
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_004);
						return objectMapper.writeValueAsString(dtoResult);
					}

					String cardNo = order.getCardNo();
					if (StringUtil.isEmpty(cardNo)) {
						return CommonUtils.createResult(dtoResult, ResultCode.ERROR_057, null);
					}

					boolean isNormal = false;
					// 根据订单号查询订单优惠详情
					List<OrderDetail> list = orderDetailService.findByOrderNo(orderNo);

					order.setPayStatus(payStatus);
					// 1、支付成功且有核心流水号 2、支付失败且有核心流水号
					if (PayStatus.Payed.getStatus().equals(payStatus)) {
						order.setTradeSno(tradeSno);
						isNormal = true;
						order.setOrderStatus(OrderStatus.Payed.getStatus());
						order.setRemark(ResultMsg.MSG_003);
						order.setPayEndTime(DateUtil.dateTimeToString(new Date()));
						order.setTradeEndTime(DateUtil.dateTimeToString(new Date()));
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
						/*
						 * Account account =
						 * this.accountService.findById(order.getAccId());
						 * JSONObject remindData = new JSONObject();
						 * remindData.put("openIdStr", account.getOpenId());
						 * remindData.put("modelType", "1");
						 * remindData.put("payValue", "￥" + order.getRealPay() /
						 * 100.0); remindData.put("cardNo", cardNo);
						 * remindData.put("tranSno", order.getOrderNo());
						 * remindData.put("tranTime", order.getTradeEndTime());
						 * remindData.put("mrchName", order.getMrchName());
						 * remindData.put("first", CommonConstants.FIRST_3);
						 * remindData.put("remark", CommonConstants.REMARK_1);
						 * TradeRemindThread tradeRemind = new
						 * TradeRemindThread(remindData); Thread thread = new
						 * Thread(tradeRemind); thread.start();
						 */
					} else if (PayStatus.PayFail.getStatus().equals(payStatus)) { // 1、支付失败且无核心流水号
						order.setOrderStatus(OrderStatus.PayFail.getStatus());
						order.setRemark(ResultMsg.MSG_002);
						dealFailOrder(activity, list, order.getOrderNo());// 非东方广场订单支付失败的相应处理
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_002);
					}
					// 查询当前余额
					CommonReturn con = postServerInfoGet.getBalanceInfo(cardNo, subCode);
					if (null != con && ResultCode.SUCCESS.equals(con.getResultCode())) {
						order.setAfterTradeBalance(((GetBalanceReceive) con.getResultData()).getBALANCE());
					}
					order.setUpdateTime(DateUtil.dateTimeToString(new Date()));
					// 保存当前的订单信息
					Order afterOrder = this.orderService.saveOrUpdate(order);
					if (isNormal) {
						DTOTradeRecord tradeRecord = OrderMapper.getInstance().mapToDTOTradeRecord(afterOrder);
						if (null != tradeRecord) {
							tradeRecord.setId(CommonUtils.getUUID());
							log.info("notify");
							tradeRecordService.saveOrUpdate(tradeRecord);
						}

						if (null != list && list.size() > 0) {
							TradeRecordDetail dto = null;
							for (OrderDetail detail : list) {
								dto = new TradeRecordDetail();
								BeanUtils.copyProperties(detail, dto);
								tradeRecordDetailService.save(dto);
							}
						}
					}
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
			} else {
				// if
				// (EastSquareConstants.EAST_SQUARE_ACTIVE.equals(eastSquareActive)&&eastSquareMrchId.equals(order.getMrchId()))
				// {
				Activity activity = postConnServerNew.getActivity(order.getMrchId(), order.getTermNo(),
						order.getSubId());
				if (activity != null && ActivityUtil.hasRandomDerateActivity(activity.getActivityItem())) {
					// 东方广场随机减活动
					if (OrderStatus.Payed.getStatus().equals(order.getOrderStatus())) {
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_001);
						return objectMapper.writeValueAsString(dtoResult);
					}

					if (OrderStatus.PayFail.getStatus().equals(order.getOrderStatus())) {
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_004);
						return objectMapper.writeValueAsString(dtoResult);
					}
					String cardNo = order.getCardNo();
					if (StringUtil.isEmpty(cardNo)) {
						return CommonUtils.createResult(dtoResult, ResultCode.ERROR_057, null);
					}
					boolean isNormal = false;
					if (StringUtil.isNotEmpty(tradeSno)) {
						order.setTradeSno(tradeSno);// 通过核心流水号查询订单详情
						GetTranByTranSnoForm form1 = new GetTranByTranSnoForm();
						form1.setTranSno(tradeSno);
						CommonReturn commonReturn = postServerInfoGet.GetTranInfoByTranSno(form1);
						if (ResultCode.SUCCESS.equals(commonReturn.getResultCode())) {
							GetTranByTranSnoReceive returnDTO = (GetTranByTranSnoReceive) commonReturn.getResultData();
							if (TranState.Normal.getState().equals(returnDTO.getTranState())) { // 核心流水号交易检查成功
								isNormal = true;
								order.setPayStatus(PayStatus.Payed.getStatus());
								order.setOrderStatus(OrderStatus.Payed.getStatus());
								order.setRemark(ResultMsg.MSG_003);
								order.setPayEndTime(DateUtil.dateTimeToString(
										CommonUtils.getTranTime(returnDTO.getTranDate(), returnDTO.getTranTime())));
								order.setTradeEndTime(DateUtil.dateTimeToString(new Date()));
								dtoResult.setResultCode(ResultCode.SUCCESS);
								dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
								Account account = this.accountService.findById(order.getAccId());
								JSONObject remindData = new JSONObject();
								remindData.put("openIdStr", account.getOpenId());
								remindData.put("modelType", "1");
								remindData.put("payValue", "￥" + order.getRealPay() / 100.0);
								remindData.put("cardNo", cardNo);
								remindData.put("tranSno", order.getOrderNo());
								remindData.put("tranTime", order.getTradeEndTime());
								remindData.put("mrchName", order.getMrchName());
								remindData.put("first", CommonConstants.FIRST_3);
								remindData.put("remark", CommonConstants.REMARK_1);
								TradeRemindThread tradeRemind = new TradeRemindThread(remindData);
								Thread thread = new Thread(tradeRemind);
								thread.start();
								// 更新沉淀池和余额池
								synchronized (lockItem) {
									this.sedimentaryBalanceService.updateByOrderNo(orderNo, 1000 * 100L);
								}

							} else { // 核心流水号交易检查失败,状态非正常！
								order.setOrderStatus(OrderStatus.Paying.getStatus());
								order.setRemark(ResultCode.getResultValue(ResultCode.ERROR_070)
										+ TranState.getTranStateString(returnDTO.getTranState()));
								dtoResult.setResultCode(ResultCode.ERROR_070);
								dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_070));
							}

						} else { // 核心流水号交易校验失败,服务异常！
							order.setOrderStatus(OrderStatus.Paying.getStatus());
							order.setRemark(ResultCode.getResultValue(ResultCode.ERROR_069));
							dtoResult.setResultCode(ResultCode.ERROR_069);
							dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_069));
						}
					} else { // 1、支付失败且无核心流水号
						order.setOrderStatus(OrderStatus.PayFail.getStatus());
						order.setRemark(ResultMsg.MSG_002);
						// 支付失败，需要将沉淀池和余额池金额回退
						dealEastSquareFailOrder(dtoResult, orderNo);
					}
					order.setUpdateTime(DateUtil.dateTimeToString(new Date()));
					// 保存当前的订单信息
					Order afterOrder = this.orderService.saveOrUpdate(order);
					if (isNormal) {
						// 查询当前余额
						CommonReturn con = postServerInfoGet.getBalanceInfo(cardNo, subCode);
						if (null != con && ResultCode.SUCCESS.equals(con.getResultCode())) {
							order.setAfterTradeBalance(((GetBalanceReceive) con.getResultData()).getBALANCE());
						}
						DTOTradeRecord tradeRecord = OrderMapper.getInstance().mapToDTOTradeRecord(afterOrder);
						if (null != tradeRecord) {
							tradeRecord.setId(CommonUtils.getUUID());
							log.info("notify");
							tradeRecordService.saveOrUpdate(tradeRecord);
						}
						// 保存订单详情
						List<OrderDetail> list = orderDetailService.findByOrderNo(orderNo);
						if (null != list && list.size() > 0) {
							TradeRecordDetail dto = null;
							for (OrderDetail detail : list) {
								dto = new TradeRecordDetail();
								BeanUtils.copyProperties(detail, dto);
								tradeRecordDetailService.save(dto);
							}
						}
					}

				} else {
					if (OrderStatus.Payed.getStatus().equals(order.getOrderStatus())) {
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_001);
						return objectMapper.writeValueAsString(dtoResult);
					}

					if (OrderStatus.PayFail.getStatus().equals(order.getOrderStatus())) {
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_004);
						return objectMapper.writeValueAsString(dtoResult);
					}

					String cardNo = order.getCardNo();
					if (StringUtil.isEmpty(cardNo)) {
						return CommonUtils.createResult(dtoResult, ResultCode.ERROR_057, null);
					}

					boolean isNormal = false;
					// 根据订单号查询订单优惠详情
					List<OrderDetail> list = orderDetailService.findByOrderNo(orderNo);

					order.setPayStatus(payStatus);
					// 1、支付成功且有核心流水号 2、支付失败且有核心流水号
					if (StringUtil.isNotEmpty(tradeSno)) {
						order.setTradeSno(tradeSno);
						// 通过核心流水号查询订单详情
						GetTranByTranSnoForm form1 = new GetTranByTranSnoForm();
						form1.setTranSno(tradeSno);
						CommonReturn commonReturn = postServerInfoGet.GetTranInfoByTranSno(form1);
						if (ResultCode.SUCCESS.equals(commonReturn.getResultCode())) {
							GetTranByTranSnoReceive returnDTO = (GetTranByTranSnoReceive) commonReturn.getResultData();
							if (TranState.Normal.getState().equals(returnDTO.getTranState())) { // 核心流水号交易检查成功
								isNormal = true;
								order.setOrderStatus(OrderStatus.Payed.getStatus());
								order.setRemark(ResultMsg.MSG_003);
								order.setPayEndTime(DateUtil.dateTimeToString(
										CommonUtils.getTranTime(returnDTO.getTranDate(), returnDTO.getTranTime())));
								order.setTradeEndTime(DateUtil.dateTimeToString(new Date()));
								dtoResult.setResultCode(ResultCode.SUCCESS);
								dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
								Account account = this.accountService.findById(order.getAccId());
								JSONObject remindData = new JSONObject();
								remindData.put("openIdStr", account.getOpenId());
								remindData.put("modelType", "1");
								remindData.put("payValue", "￥" + order.getRealPay() / 100.0);
								remindData.put("cardNo", cardNo);
								remindData.put("tranSno", order.getOrderNo());
								remindData.put("tranTime", order.getTradeEndTime());
								remindData.put("mrchName", order.getMrchName());
								remindData.put("first", CommonConstants.FIRST_3);
								remindData.put("remark", CommonConstants.REMARK_1);
								TradeRemindThread tradeRemind = new TradeRemindThread(remindData);
								Thread thread = new Thread(tradeRemind);
								thread.start();
							} else { // 核心流水号交易检查失败,状态非正常！
								order.setOrderStatus(OrderStatus.Paying.getStatus());
								order.setRemark(ResultCode.getResultValue(ResultCode.ERROR_070)
										+ TranState.getTranStateString(returnDTO.getTranState()));
								dtoResult.setResultCode(ResultCode.ERROR_070);
								dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_070));
							}

						} else { // 核心流水号交易校验失败,服务异常！
							order.setOrderStatus(OrderStatus.Paying.getStatus());
							order.setRemark(ResultCode.getResultValue(ResultCode.ERROR_069));
							dtoResult.setResultCode(ResultCode.ERROR_069);
							dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_069));
						}
					} else { // 1、支付失败且无核心流水号
						order.setOrderStatus(OrderStatus.PayFail.getStatus());
						order.setRemark(ResultMsg.MSG_002);
						dealFailOrder(activity, list, order.getOrderNo());// 非东方广场订单支付失败的相应处理
						dtoResult.setResultCode(ResultCode.SUCCESS);
						dtoResult.setResultMsg(ResultMsg.MSG_002);
					}

					// 查询当前余额
					CommonReturn con = postServerInfoGet.getBalanceInfo(cardNo, subCode);
					if (null != con && ResultCode.SUCCESS.equals(con.getResultCode())) {
						order.setAfterTradeBalance(((GetBalanceReceive) con.getResultData()).getBALANCE());
					}

					order.setUpdateTime(DateUtil.dateTimeToString(new Date()));
					// 保存当前的订单信息
					Order afterOrder = this.orderService.saveOrUpdate(order);
					if (isNormal) {
						DTOTradeRecord tradeRecord = OrderMapper.getInstance().mapToDTOTradeRecord(afterOrder);
						if (null != tradeRecord) {
							tradeRecord.setId(CommonUtils.getUUID());
							log.info("notify");
							tradeRecordService.saveOrUpdate(tradeRecord);
						}

						if (null != list && list.size() > 0) {
							TradeRecordDetail dto = null;
							for (OrderDetail detail : list) {
								dto = new TradeRecordDetail();
								BeanUtils.copyProperties(detail, dto);
								tradeRecordDetailService.save(dto);
							}
						}

						// 商户扫描二维码交易
						try {
							TranUserQRCodeByHttpForm form = new TranUserQRCodeByHttpForm();
							form.setQrcodeNo(afterOrder.getQrcodeNo());
							form.setActTranAmt(afterOrder.getRealPay() + "");
							form.setBalance(afterOrder.getAfterTradeBalance());
							form.setMerchantId(afterOrder.getMrchId());
							form.setPsamId(afterOrder.getPsamId());
							form.setShopName(afterOrder.getMrchName());
							form.setShopType(afterOrder.getMrchType());
							form.setShouldTranAmt(afterOrder.getNeedPay() + "");
							form.setSubCode(afterOrder.getSubId());
							form.setTranRemark(afterOrder.getRemark());
							form.setSwiftNumber(afterOrder.getTradeSno());
							postServerInfoGet.tranUserQRCodeByHttp(form);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			dtoResult.setResultCode(ResultCode.FAIL);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.FAIL));
		} finally {
			try {
				// 返回响应
				responseJson = objectMapper.writeValueAsString(dtoResult);// 实体转json
			} catch (Exception e) {
				e.printStackTrace();
			}
			return responseJson;
		}
	}
	
	/**
	 * 用户根据二维码查询订单号交易信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getOrderInfoByQRCode", method = RequestMethod.POST)
	public String getOrderInfoByQRCode(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String qrCode = jo.getString("qrcode_no");

			if (StringUtil.isEmpty(qrCode)) {
				dtoResult.setResultCode(ResultCode.ERROR_046);
				dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_046));
				return objectMapper.writeValueAsString(dtoResult);
			}
			String string = orderService.getOrderInfoByQRCode(qrCode);
			if (null != string) {
				return string;
			}
			dtoResult.setResultCode(ResultCode.FAIL);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.FAIL));
			return objectMapper.writeValueAsString(dtoResult);
		} catch (Exception e) {
			dtoResult.setResultCode(ResultCode.FAIL);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.FAIL));
			try {
				return objectMapper.writeValueAsString(dtoResult);
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
				return "";
			}
		}

	}
	
	/**
	 * 根据订单编号查询订单信息
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("finally")
	@ResponseBody
	@RequestMapping(value = "/getDetailByOrderNo", method = RequestMethod.POST)
	public String getDetailByOrderNo(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String responseJson = "";
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String orderNo = jo.getString("order_no");
			if (StringUtil.isEmpty(orderNo)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_048, null);
			}
			DTOOrder order = this.orderService.getByOrderNo(orderNo);// 根据订单编号查询订单
			if (order == null) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_047, null);
			}
			// 如果成功就查询详情
			List<OrderDetail> detailList = null;
			if (OrderStatus.Payed.getStatus().equals(order.getOrderStatus())) {
				// 根据订单编号查询订单详情
				detailList = this.orderDetailService.findByOrderNo(orderNo);
			}
			JSONObject result = createRetOrderDetail(order, detailList);
			boolean isHandRedpacket = false;
			if (isHandRedpacket) {
				result.put("is_create_red_packet", CommonStatus.TRUE);
			} else {
				result.put("is_create_red_packet", CommonStatus.FALSE);
			}
			result.put("description", null);
			dtoResult.setResultCode(ResultCode.SUCCESS);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
			dtoResult.setResultData(objectMapper.writeValueAsString(result));
		} catch (Exception e) {
			e.printStackTrace();
			dtoResult.setResultCode(ResultCode.FAIL);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.FAIL));
		} finally {
			try {
				// 返回响应
				responseJson = objectMapper.writeValueAsString(dtoResult);// 实体转json
			} catch (Exception e) {
				e.printStackTrace();
			}
			return responseJson;
		}
	}
	
	/**
	 * 用户确认二维码支付
	 * 
	 * @param request
	 * @return
	 * @throws JsonProcessingException
	 */
	@RequestMapping(value = "/confirmQRcodePay", method = RequestMethod.POST)
	@ResponseBody
	public String confirmQRcodePay(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		String sendData = "";
		try {
			sendData = request.getParameter("sendData");
			// 入参为空判断
			if (StringUtil.isEmpty(sendData)) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			DTOConfirmQRcodePayForm in = objectMapper.readValue(sendData, DTOConfirmQRcodePayForm.class);
			if (StringUtil.isEmpty(in.getOrder_no())) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_048, null);
			}
			if (StringUtil.isEmpty(in.getRandom_num())) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_084, null);
			}
			if (StringUtil.isEmpty(in.getCard_tran_seq())) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_083, null);
			}
			// 检查订单是否存在
			DTOOrder order = orderService.getByOrderNo(in.getOrder_no());
			if (null == order) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_047, null);
			}

			// 查看当前订单状态，避免重复支付
			if (StringUtil.isEmpty(order.getOrderStatus())) {
				log.error("订单状态为空，订单异常！");
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_128, null);
			}

			if (OrderStatus.Paying.getStatus().equals(order.getOrderStatus())) {
				log.error("订单处理支付处理中，不能重复支付！");
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_129, null);
			}

			if (OrderStatus.Payed.getStatus().equals(order.getOrderStatus())) {
				log.error("订单处理成功，不能重复支付！");
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_129, null);
			}

			if (!OrderStatus.Unpay.getStatus().equals(order.getOrderStatus())) {
				log.error("订单已经在处理，不能重复支付！");
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_131, null);
			}

			// 修改当前订单为支付中
			orderService.updateOrder(order, OrderStatus.Paying.getStatus());

			// 校验优惠券是否合法（放置在优惠券同时被使用）
			// 代理联机交易
			CommonReturn con = QRLinkNetTrade(dtoResult, in, order);
			if (ResultCode.FAIL.equals(con.getResultCode())) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_085, null);
			}

			if (ResultCode.ERROR_086.equals(con.getResultCode())) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_086, null);
			}

			if (ResultCode.ERROR_034.equals(con.getResultCode())) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_034, null);
			}
			String tradeEndTime = DateUtil.dateTimeToString(new Date());
			try {
				// 查询当前余额,作为交易卡后余额
				CommonReturn bala = postServerInfoGet.getBalanceInfo(order.getCardNo(), subCode);
				if (null != bala && ResultCode.SUCCESS.equals(bala.getResultCode())) {
					GetBalanceReceive receive = (GetBalanceReceive) bala.getResultData();
					order.setAfterTradeBalance(receive.getBALANCE());
				}
				order.setTradeSno(((LinkNetTradeReceive) con.getResultData()).getTran_sno());
				order.setTradeEndTime(tradeEndTime);
				order.setPayment(PayStatus.Payed.getStatus());
				order.setPayEndTime(tradeEndTime);
				// 修改订单、优惠券状态
				Order afterOrder = orderService.updateOrder(order, PayStatus.Payed.getStatus());
				// 修改优惠券状态
				Account account = this.accountService.findById(order.getAccId());
				JSONObject remindData = new JSONObject();
				remindData.put("openIdStr", account.getOpenId());
				remindData.put("modelType", "1");
				remindData.put("payValue", "￥" + order.getRealPay() / 100.0);
				remindData.put("cardNo", order.getCardNo());
				remindData.put("tranSno", order.getOrderNo());
				remindData.put("tranTime", order.getTradeEndTime());
				remindData.put("mrchName", order.getMrchName());
				remindData.put("first", CommonConstants.FIRST_3);
				remindData.put("remark", CommonConstants.REMARK_1);
				TradeRemindThread tradeRemind = new TradeRemindThread(remindData);
				Thread thread = new Thread(tradeRemind);
				thread.start();
				// 存入交易记录
				DTOTradeRecord tradeRecord = OrderMapper.getInstance().mapToDTOTradeRecord(afterOrder);
				if (null != tradeRecord) {
					tradeRecord.setId(CommonUtils.getUUID());
					log.info("confirmQRcodePay");
					tradeRecordService.saveOrUpdate(tradeRecord);
				}
				// 存储交易记录详情表
				List<OrderDetail> list = orderDetailService.findByOrderNo(order.getOrderNo());
				if (null != list && list.size() > 0) {
					TradeRecordDetail dtoDetail = null;
					for (OrderDetail detail : list) {
						dtoDetail = new TradeRecordDetail();
						BeanUtils.copyProperties(detail, dtoDetail);
						tradeRecordDetailService.save(dtoDetail);
					}
				}
			} catch (Exception e) {
				log.error("扫码交易成功，存储交易记录或交易记录详情失败！");
				e.printStackTrace();
			}
			// 查询返回参数
			DTOConfirmQRcodeReturn dtoReturn = confirmQRcodeReturn(order, tradeEndTime);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(dtoReturn));
		} catch (Exception e) {
			e.printStackTrace();
			// 日志记录
			log.info(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_UserConfirmQrcodePay
					+ ",请求数据:入参为:" + sendData + "  出错:" + e);
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_058, null);
		} finally {
			// 日志记录
			log.info(DateUtil.dateTimeToString(new Date()) + "调用接口：" + InterfaceDsc.APP_WXXNK_UserConfirmQrcodePay
					+ ",请求数据:入参为:" + sendData + "  返回参数:" + dtoResult);
		}
	}

	/**
	 * 生成随机减(东方广场)订单详情
	 * 
	 * @param order
	 * @param strategyResult
	 * @return
	 */
	private DTOOrderDetail createEastSquareOrderDetail(DTOOrder order, StrategyResult strategyResult) {
		if (!strategyResult.isFlag() || strategyResult.getOrderDetailList() == null
				|| strategyResult.getOrderDetailList().size() <= 0)
			return null;
		List<CreateOrderDetailBean> orderDetailList = strategyResult.getOrderDetailList();
		CreateOrderDetailBean bean = orderDetailList.get(0);
		DTOOrderDetail orderDetail = new DTOOrderDetail();
		orderDetail.setId(CommonUtils.getUUID());
		orderDetail.setCreateTime(DateUtil.dateTimeToString(new Date()));
		orderDetail.setUpdateTime(DateUtil.dateTimeToString(new Date()));
		orderDetail.setOrderNo(order.getOrderNo());
		orderDetail.setRelateId(bean.getRaletedId());
		orderDetail.setIsDeleted(false);
		orderDetail.setDiscountType(bean.getDiscountType());
		orderDetail.setDiscountAmount(bean.getDiscountAmount() + "");
		orderDetail.setDiscountValue(bean.getDiscountValue());
		orderDetail.setProductName(bean.getProductName());
		orderDetail.setActivityItemType(bean.getActivityItemType());
		if (DetailType.ActivityDiscount.getKey().equals(bean.getType())) {
			orderDetail.setType(DetailType.ActivityDiscount.getKey());
		}
		return orderDetail;
	}

	/**
	 * 用户创建二维码创建订单入参校验
	 * 
	 * @param dtoResult
	 * @param in
	 * @return
	 */
	private String createQrcodeOrderJudge(DTOResult dtoResult, DTOCreateOrderFormEcard in) {

		if (StringUtil.isEmpty(in.getAccount_id())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
		}
		if (StringUtil.isEmpty(in.getQrcode_no())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_046, null);
		}
		if (StringUtil.isEmpty(in.getOrder_type())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_053, null);
		}
		if (StringUtil.isEmpty(in.getTrade_type())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_078, null);
		}
		if (StringUtil.isEmpty(in.getMrch_id())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_077, null);
		}
		if (StringUtil.isEmpty(in.getTerm_no())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_080, null);
		}
		if (StringUtil.isEmpty(in.getSub_code())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_074, null);
		}
		if (StringUtil.isEmpty(in.getNeed_pay())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_055, null);
		}
		if(StringUtil.isEmpty(in.getCard_no())) {
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_156, null);
		}

		return ResultCode.SUCCESS;
	}

	/**
	 * 用户扫商户后台后台优惠策略
	 * 
	 * @param account
	 * @param needPay
	 * @param vipRate
	 * @param mchRate
	 * @param empRate
	 * @param vipProduct
	 * @param mrchDetail
	 * @param in
	 * @param couponDetailBeans
	 * @return
	 */
	private List<CreateOrderDetailBean> qrBackendDiscountStrategy(Account account, Long needPay,
			Long mchRate, Long empRate, GenerateMrchTwoCode mrchDetail) {
		List<CreateOrderDetailBean> beans = new ArrayList<CreateOrderDetailBean>();
		Long realPay = needPay;
		Long minConsumption = Long.parseLong(minConSum);
		// 比较VIP折扣率，选择折扣率最小进行，并返回响应的对象
		CreateOrderDetailBean discountBean = CommonUtils.getMinDiscouRate(needPay, mchRate, empRate, mrchDetail);
		// System.out.println("商户折扣:"+mchRate+",VIP折扣:"+vipRate+",海航员工折扣:"+empRate+",最终使用折扣:"+discountBean);
		// 折扣金额
		Long disCountAmount = 0l;
		if (null != discountBean) {
			beans.add(discountBean);
			disCountAmount = discountBean.getDiscountAmount();
		}
		// 打折后得到实际支付金额
		realPay = needPay - disCountAmount;
		// 打折后有最低消费，满减可以为0
		if (realPay <= minConsumption) {
			realPay = minConsumption;
		}
		return beans;
	}
	
	private DTOTradeRecord mapperRecord(DTOOrder orderDto) {
		DTOTradeRecord dtoTradeRecord = new DTOTradeRecord();
		BeanUtils.copyProperties(orderDto, dtoTradeRecord, new String[] { "id" });
		dtoTradeRecord.setId(CommonUtils.getUUID());
		return dtoTradeRecord;
	}
	
	/**
	 * 处理东方广场支付失败的订单
	 * 
	 * @param dtoResult
	 * @param orderNo
	 */
	private void dealEastSquareFailOrder(DTOResult dtoResult, String orderNo) {
//		Jedis jedis = jedisUtil.getJedis();
		Jedis jedis = jedisPoolUtil.getJedis();
		SediBalanceChangeRecord changeRecord = this.sediBalanceChangeRecordService.findByOrderNo(orderNo);//
		try {
			synchronized (lockItem) {
				Long balance = jedis.incrBy("balance", changeRecord.getBalanceChange());
				Long sedimentary = jedis.decrBy("sedimentary", changeRecord.getSedimentaryChange());
				jedis.decrBy("eastSquareCount", 1);
				jedis.decrBy("eastSquareAmount", changeRecord.getBalanceChange());
				SedimentaryBalance findSingleResult = this.sedimentaryBalanceService.findSingleResult();
				findSingleResult.setBalance(balance);
				findSingleResult.setSedimentary(sedimentary);
				this.sedimentaryBalanceService.failBack(findSingleResult, changeRecord);
			}
			dtoResult.setResultCode(ResultCode.SUCCESS);
			dtoResult.setResultMsg(ResultMsg.MSG_002);
		} catch (Exception e) {
			e.printStackTrace();// 交易失败回退异常
			log.info("orderNo:" + orderNo + ",交易失败，回退异常，" + e.getMessage());
			jedis.decrBy("balance", changeRecord.getBalanceChange());
			jedis.incrBy("sedimentary", changeRecord.getSedimentaryChange());
			jedis.incrBy("eastSquareCount", 1);
			jedis.incrBy("eastSquareAmount", changeRecord.getBalanceChange());
		} finally {
//			jedisUtil.closeJedis(jedis);
			if(jedis != null) jedis.close();
		}
	}
	
	/**
	 * 处理支付失败的订单
	 * 
	 * @param activity
	 * @param list
	 */
	private void dealFailOrder(Activity activity, List<OrderDetail> list, String orderNo) {
		if (activity != null && activity.getActivityItem() != null && activity.getActivityItem().size() > 0) {
			for (ActivityItem activityItem : activity.getActivityItem()) {
				if (ActivityType.CGDZ.getType().equals(activityItem.getSubType())) {// 常规打折活动项
//					Jedis jedis = jedisUtil.getJedis();
					Jedis jedis = jedisPoolUtil.getJedis();
					try {
						OrderDetail detail = this.orderDetailService.findByOrderNoAndItemId(orderNo,
								activityItem.getId());
						if (detail != null) {
							String key = ActivityUtil.getCgdzActivityKey(activity.getId());
							Long decrBy = jedis.decrBy(key, 1);// 将常规打折活动的笔数减回去
							log.info("异步通知失败常规打折笔数回退:key" + key + ",val:" + decrBy);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
//						jedisUtil.closeJedis(jedis);
						if(jedis != null) jedis.close();
					}
				} else if (ActivityType.MJ1.getType().equals(activityItem.getSubType())) {
//					Jedis jedis = jedisUtil.getJedis();
					Jedis jedis = jedisPoolUtil.getJedis();
					try {
						OrderDetail detail = this.orderDetailService.findByOrderNoAndItemId(orderNo,
								activityItem.getId());
						if (detail != null) {
							String key = ActivityUtil.getMjActivityKey(activity.getId());
							Long decrBy = jedis.decrBy(key, 1);// 将常规打折活动的笔数减回去
							log.info("异步通知失败满减优惠1笔数回退:key" + key + ",val:" + decrBy);
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
//						jedisUtil.closeJedis(jedis);
						if(jedis != null) jedis.close();
					}
				}
			}
		}

	}
	
	/**
	 * 创建返回的订单信息和订单详情信息对象
	 * 
	 * @param order
	 * @param detailList
	 * @return
	 */
	private JSONObject createRetOrderDetail(DTOOrder order, List<OrderDetail> detailList) {
		JSONObject jo = new JSONObject();
		jo.put("account_id", order.getAccId());
		jo.put("card_no", order.getCardNo());
		jo.put("mrch_id", order.getMrchId());
		jo.put("mrch_name", order.getMrchName());
		jo.put("mrch_type", order.getMrchType());
		jo.put("need_pay", order.getNeedPay().toString());
		jo.put("order_no", order.getOrderNo());
		jo.put("order_status", order.getOrderStatus());
		jo.put("payment", order.getPayment());
		jo.put("psam_id", order.getPsamId());
		jo.put("real_pay", order.getRealPay().toString());
		JSONArray detailObj = new JSONArray();
		JSONObject vip = null;
		JSONObject mrch = null;
		JSONObject employee = null;

		if (detailList != null && detailList.size() > 0) {
			OrderDetail mrchDetail = null;
			OrderDetail vipDetail = null;
			OrderDetail employeeDetail = null;
			List<OrderDetail> couponDetails = new ArrayList<OrderDetail>();
			List<OrderDetail> activityDetails = new ArrayList<OrderDetail>();
			for (OrderDetail od : detailList) {
				if (DetailType.MrchDiscount.getKey().equals(od.getType())) {
					mrchDetail = od;// 商户打折
				} else if (DetailType.VIP.getKey().equals(od.getType())) {
					vipDetail = od;// vip打折
				} else if (DetailType.COUPON.getKey().equals(od.getType())) {
					couponDetails.add(od);// 代金券
				} else if (DetailType.EmpDiscount.getKey().equals(od.getType())) {
					employeeDetail = od;// 海航员工折扣
				} else if (DetailType.ActivityDiscount.getKey().equals(od.getType())) {
					activityDetails.add(od);// 活动优惠
				}
			}
			SediBalanceChangeRecord findByOrderNo = this.sediBalanceChangeRecordService
					.findByOrderNo(order.getOrderNo());
			if (findByOrderNo != null && StringUtil.isNotEmpty(findByOrderNo.getDescription())) {
				JSONObject manjian = new JSONObject();
				manjian.put("discount_name", "随机减活动");
				manjian.put("discount_detail", findByOrderNo.getDescription());
				detailObj.add(manjian);
			}
			if (null != employeeDetail) {
				employee = new JSONObject();
				employee.put("discount_name", "员工折扣");
				employee.put("discount_detail", employeeDetail.getDiscountValue() + "折，优惠"
						+ (Long.valueOf(employeeDetail.getDiscountAmount()) / 100.0) + "元");
				detailObj.add(employee);
			}

			if (mrchDetail != null) {
				mrch = new JSONObject();
				mrch.put("discount_name", "商户折扣");
				mrch.put("discount_detail", mrchDetail.getDiscountValue() + "折，优惠"
						+ (Long.valueOf(mrchDetail.getDiscountAmount()) / 100.0) + "元");
				detailObj.add(mrch);
			}
			if (vipDetail != null) {
				vip = new JSONObject();
				vip.put("discount_name", "VIP折扣");
				vip.put("discount_detail", vipDetail.getDiscountValue() + "折，优惠"
						+ (Long.valueOf(vipDetail.getDiscountAmount()) / 100.0) + "元");
				detailObj.add(vip);
			}
			for (OrderDetail od : couponDetails) {
				JSONObject coupon = new JSONObject();
				coupon.put("discount_name", "优惠券：" + od.getCouponTypeName());
				coupon.put("discount_detail", "优惠" + (Long.valueOf(od.getDiscountAmount()) / 100.0) + "元");
				detailObj.add(coupon);
			}
			for (OrderDetail od : activityDetails) {
				JSONObject temp = new JSONObject();
				if (ActivityType.SJJ.getType().equals(od.getActivityItemType()))
					continue;
				temp.put("discount_name", od.getProductName() + "活动");
				temp.put("discount_detail", "优惠" + (Long.valueOf(od.getDiscountAmount()) / 100.0) + "元");
				detailObj.add(temp);

			}
			jo.put("order_detail", detailObj);
		}
		return jo;
	}
	
	/**
	 * 代理联机消费
	 * 
	 * @param dtoResult
	 * @param in
	 * @param order
	 * @return
	 * @throws Exception
	 */
	private CommonReturn QRLinkNetTrade(DTOResult dtoResult, DTOConfirmQRcodePayForm in, DTOOrder order)
			throws Exception {
		LinkNetTradeForm form = new LinkNetTradeForm();
		form.setCardBlance("0");
		form.setCardNo(order.getCardNo());
		form.setCardTranSeq(in.getCard_tran_seq());
		form.setMac1(in.getMac1());
		form.setMerchantId(order.getMrchId());
		form.setMrchId(order.getMrchId());
		form.setPasmId("");
		form.setPasmTermId(order.getTermNo());
		form.setPassword(in.getPassword());
		form.setProxyEqpIdl(order.getTermNo());
		form.setRandomNum(in.getRandom_num());
		form.setTranAmt(order.getRealPay() + "");
		form.setSubCode(order.getSubId());
		form.setTranValue(order.getNeedPay() + "");
		form.setOrderNo(order.getOrderNo());// 联机交易增加订单号传送给核心

		CommonReturn con = postServerInfoGet.linkNetTrade(form);
		return con;
	}
	
	private DTOConfirmQRcodeReturn confirmQRcodeReturn(DTOOrder order, String tradeEndTime) {
		DTOConfirmQRcodeReturn dtoReturn = new DTOConfirmQRcodeReturn();
		dtoReturn.setDiscount(order.getRemark());
		dtoReturn.setMrch_name(order.getMrchName());
		dtoReturn.setNeed_pay(order.getNeedPay() + "");
		dtoReturn.setOrder_no(order.getOrderNo());
		dtoReturn.setOrder_status(PayStatus.Payed.getStatus());
		dtoReturn.setOrder_type_name(order.getOrderTypeName());
		dtoReturn.setPayment(PaymentType.getPaymentTypeString(order.getPayment()));
		dtoReturn.setReal_pay(order.getRealPay() + "");
		dtoReturn.setTrade_end_time(tradeEndTime);
		dtoReturn.setTrade_sno(order.getTradeSno());
		dtoReturn.setTrade_type(order.getTradeType());
		return dtoReturn;
	}
	
}
